blob: 03a117f435420b86d653a63e20bf751c55e770dc [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 Topper11899b02018-06-05 21:54:35 +00002610 i = 1; l = 0; u = 1;
2611 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002612 case X86::BI__builtin_ia32_vec_set_v2di:
2613 i = 2; l = 0; u = 1;
2614 break;
Craig Topper11899b02018-06-05 21:54:35 +00002615 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002616 case X86::BI__builtin_ia32_vec_ext_v4si:
2617 case X86::BI__builtin_ia32_vec_ext_v4sf:
2618 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper11899b02018-06-05 21:54:35 +00002619 i = 1; l = 0; u = 3;
2620 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002621 case X86::BI_mm_prefetch:
2622 case X86::BI__builtin_ia32_vec_ext_v8hi:
2623 case X86::BI__builtin_ia32_vec_ext_v8si:
2624 i = 1; l = 0; u = 7;
2625 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002626 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper11899b02018-06-05 21:54:35 +00002627 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002628 case X86::BI__builtin_ia32_vec_set_v4si:
2629 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00002630 case X86::BI__builtin_ia32_shuf_f32x4_256:
2631 case X86::BI__builtin_ia32_shuf_f64x2_256:
2632 case X86::BI__builtin_ia32_shuf_i32x4_256:
2633 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper39c87102016-05-18 03:18:12 +00002634 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002635 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002636 case X86::BI__builtin_ia32_vpermil2pd:
2637 case X86::BI__builtin_ia32_vpermil2pd256:
2638 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002639 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002640 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002641 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002642 case X86::BI__builtin_ia32_cmpb128_mask:
2643 case X86::BI__builtin_ia32_cmpw128_mask:
2644 case X86::BI__builtin_ia32_cmpd128_mask:
2645 case X86::BI__builtin_ia32_cmpq128_mask:
2646 case X86::BI__builtin_ia32_cmpb256_mask:
2647 case X86::BI__builtin_ia32_cmpw256_mask:
2648 case X86::BI__builtin_ia32_cmpd256_mask:
2649 case X86::BI__builtin_ia32_cmpq256_mask:
2650 case X86::BI__builtin_ia32_cmpb512_mask:
2651 case X86::BI__builtin_ia32_cmpw512_mask:
2652 case X86::BI__builtin_ia32_cmpd512_mask:
2653 case X86::BI__builtin_ia32_cmpq512_mask:
2654 case X86::BI__builtin_ia32_ucmpb128_mask:
2655 case X86::BI__builtin_ia32_ucmpw128_mask:
2656 case X86::BI__builtin_ia32_ucmpd128_mask:
2657 case X86::BI__builtin_ia32_ucmpq128_mask:
2658 case X86::BI__builtin_ia32_ucmpb256_mask:
2659 case X86::BI__builtin_ia32_ucmpw256_mask:
2660 case X86::BI__builtin_ia32_ucmpd256_mask:
2661 case X86::BI__builtin_ia32_ucmpq256_mask:
2662 case X86::BI__builtin_ia32_ucmpb512_mask:
2663 case X86::BI__builtin_ia32_ucmpw512_mask:
2664 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002665 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002666 case X86::BI__builtin_ia32_vpcomub:
2667 case X86::BI__builtin_ia32_vpcomuw:
2668 case X86::BI__builtin_ia32_vpcomud:
2669 case X86::BI__builtin_ia32_vpcomuq:
2670 case X86::BI__builtin_ia32_vpcomb:
2671 case X86::BI__builtin_ia32_vpcomw:
2672 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002673 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002674 case X86::BI__builtin_ia32_vec_set_v8hi:
2675 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002676 i = 2; l = 0; u = 7;
2677 break;
2678 case X86::BI__builtin_ia32_roundps:
2679 case X86::BI__builtin_ia32_roundpd:
2680 case X86::BI__builtin_ia32_roundps256:
2681 case X86::BI__builtin_ia32_roundpd256:
Craig Topperf3914b72018-06-06 00:24:55 +00002682 case X86::BI__builtin_ia32_vec_ext_v16qi:
2683 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002684 i = 1; l = 0; u = 15;
2685 break;
2686 case X86::BI__builtin_ia32_roundss:
2687 case X86::BI__builtin_ia32_roundsd:
2688 case X86::BI__builtin_ia32_rangepd128_mask:
2689 case X86::BI__builtin_ia32_rangepd256_mask:
2690 case X86::BI__builtin_ia32_rangepd512_mask:
2691 case X86::BI__builtin_ia32_rangeps128_mask:
2692 case X86::BI__builtin_ia32_rangeps256_mask:
2693 case X86::BI__builtin_ia32_rangeps512_mask:
2694 case X86::BI__builtin_ia32_getmantsd_round_mask:
2695 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002696 case X86::BI__builtin_ia32_vec_set_v16qi:
2697 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002698 i = 2; l = 0; u = 15;
2699 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002700 case X86::BI__builtin_ia32_vec_ext_v32qi:
2701 i = 1; l = 0; u = 31;
2702 break;
Craig Topper39c87102016-05-18 03:18:12 +00002703 case X86::BI__builtin_ia32_cmpps:
2704 case X86::BI__builtin_ia32_cmpss:
2705 case X86::BI__builtin_ia32_cmppd:
2706 case X86::BI__builtin_ia32_cmpsd:
2707 case X86::BI__builtin_ia32_cmpps256:
2708 case X86::BI__builtin_ia32_cmppd256:
2709 case X86::BI__builtin_ia32_cmpps128_mask:
2710 case X86::BI__builtin_ia32_cmppd128_mask:
2711 case X86::BI__builtin_ia32_cmpps256_mask:
2712 case X86::BI__builtin_ia32_cmppd256_mask:
2713 case X86::BI__builtin_ia32_cmpps512_mask:
2714 case X86::BI__builtin_ia32_cmppd512_mask:
2715 case X86::BI__builtin_ia32_cmpsd_mask:
2716 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002717 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002718 i = 2; l = 0; u = 31;
2719 break;
Craig Topper39c87102016-05-18 03:18:12 +00002720 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002721 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002722 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002723 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2724 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002725 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2726 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2727 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2728 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2729 case X86::BI__builtin_ia32_rndscaleps_mask:
2730 case X86::BI__builtin_ia32_rndscalepd_mask:
2731 case X86::BI__builtin_ia32_reducepd128_mask:
2732 case X86::BI__builtin_ia32_reducepd256_mask:
2733 case X86::BI__builtin_ia32_reducepd512_mask:
2734 case X86::BI__builtin_ia32_reduceps128_mask:
2735 case X86::BI__builtin_ia32_reduceps256_mask:
2736 case X86::BI__builtin_ia32_reduceps512_mask:
2737 case X86::BI__builtin_ia32_prold512_mask:
2738 case X86::BI__builtin_ia32_prolq512_mask:
2739 case X86::BI__builtin_ia32_prold128_mask:
2740 case X86::BI__builtin_ia32_prold256_mask:
2741 case X86::BI__builtin_ia32_prolq128_mask:
2742 case X86::BI__builtin_ia32_prolq256_mask:
2743 case X86::BI__builtin_ia32_prord128_mask:
2744 case X86::BI__builtin_ia32_prord256_mask:
2745 case X86::BI__builtin_ia32_prorq128_mask:
2746 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002747 case X86::BI__builtin_ia32_fpclasspd128_mask:
2748 case X86::BI__builtin_ia32_fpclasspd256_mask:
2749 case X86::BI__builtin_ia32_fpclassps128_mask:
2750 case X86::BI__builtin_ia32_fpclassps256_mask:
2751 case X86::BI__builtin_ia32_fpclassps512_mask:
2752 case X86::BI__builtin_ia32_fpclasspd512_mask:
2753 case X86::BI__builtin_ia32_fpclasssd_mask:
2754 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002755 i = 1; l = 0; u = 255;
2756 break;
Craig Topper39c87102016-05-18 03:18:12 +00002757 case X86::BI__builtin_ia32_palignr128:
2758 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002759 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00002760 case X86::BI__builtin_ia32_alignq512:
2761 case X86::BI__builtin_ia32_alignd512:
2762 case X86::BI__builtin_ia32_alignd128:
2763 case X86::BI__builtin_ia32_alignd256:
2764 case X86::BI__builtin_ia32_alignq128:
2765 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00002766 case X86::BI__builtin_ia32_vcomisd:
2767 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00002768 case X86::BI__builtin_ia32_shuf_f32x4:
2769 case X86::BI__builtin_ia32_shuf_f64x2:
2770 case X86::BI__builtin_ia32_shuf_i32x4:
2771 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper39c87102016-05-18 03:18:12 +00002772 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2773 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2774 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002775 case X86::BI__builtin_ia32_vpshldd128_mask:
2776 case X86::BI__builtin_ia32_vpshldd256_mask:
2777 case X86::BI__builtin_ia32_vpshldd512_mask:
2778 case X86::BI__builtin_ia32_vpshldq128_mask:
2779 case X86::BI__builtin_ia32_vpshldq256_mask:
2780 case X86::BI__builtin_ia32_vpshldq512_mask:
2781 case X86::BI__builtin_ia32_vpshldw128_mask:
2782 case X86::BI__builtin_ia32_vpshldw256_mask:
2783 case X86::BI__builtin_ia32_vpshldw512_mask:
2784 case X86::BI__builtin_ia32_vpshrdd128_mask:
2785 case X86::BI__builtin_ia32_vpshrdd256_mask:
2786 case X86::BI__builtin_ia32_vpshrdd512_mask:
2787 case X86::BI__builtin_ia32_vpshrdq128_mask:
2788 case X86::BI__builtin_ia32_vpshrdq256_mask:
2789 case X86::BI__builtin_ia32_vpshrdq512_mask:
2790 case X86::BI__builtin_ia32_vpshrdw128_mask:
2791 case X86::BI__builtin_ia32_vpshrdw256_mask:
2792 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002793 i = 2; l = 0; u = 255;
2794 break;
2795 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2796 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2797 case X86::BI__builtin_ia32_fixupimmps512_mask:
2798 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2799 case X86::BI__builtin_ia32_fixupimmsd_mask:
2800 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2801 case X86::BI__builtin_ia32_fixupimmss_mask:
2802 case X86::BI__builtin_ia32_fixupimmss_maskz:
2803 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2804 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2805 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2806 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2807 case X86::BI__builtin_ia32_fixupimmps128_mask:
2808 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2809 case X86::BI__builtin_ia32_fixupimmps256_mask:
2810 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2811 case X86::BI__builtin_ia32_pternlogd512_mask:
2812 case X86::BI__builtin_ia32_pternlogd512_maskz:
2813 case X86::BI__builtin_ia32_pternlogq512_mask:
2814 case X86::BI__builtin_ia32_pternlogq512_maskz:
2815 case X86::BI__builtin_ia32_pternlogd128_mask:
2816 case X86::BI__builtin_ia32_pternlogd128_maskz:
2817 case X86::BI__builtin_ia32_pternlogd256_mask:
2818 case X86::BI__builtin_ia32_pternlogd256_maskz:
2819 case X86::BI__builtin_ia32_pternlogq128_mask:
2820 case X86::BI__builtin_ia32_pternlogq128_maskz:
2821 case X86::BI__builtin_ia32_pternlogq256_mask:
2822 case X86::BI__builtin_ia32_pternlogq256_maskz:
2823 i = 3; l = 0; u = 255;
2824 break;
Craig Topper9625db02017-03-12 22:19:10 +00002825 case X86::BI__builtin_ia32_gatherpfdpd:
2826 case X86::BI__builtin_ia32_gatherpfdps:
2827 case X86::BI__builtin_ia32_gatherpfqpd:
2828 case X86::BI__builtin_ia32_gatherpfqps:
2829 case X86::BI__builtin_ia32_scatterpfdpd:
2830 case X86::BI__builtin_ia32_scatterpfdps:
2831 case X86::BI__builtin_ia32_scatterpfqpd:
2832 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002833 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002834 break;
Craig Topper39c87102016-05-18 03:18:12 +00002835 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2836 case X86::BI__builtin_ia32_rndscaless_round_mask:
2837 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002838 break;
Craig Topperd3623152018-06-07 17:28:03 +00002839 case X86::BI__builtin_ia32_pslldqi128:
2840 case X86::BI__builtin_ia32_pslldqi256:
2841 case X86::BI__builtin_ia32_pslldqi512:
2842 case X86::BI__builtin_ia32_psrldqi128:
2843 case X86::BI__builtin_ia32_psrldqi256:
2844 case X86::BI__builtin_ia32_psrldqi512:
2845 i = 1; l = 0; u = 1023;
2846 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002847 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002848 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002849}
2850
Richard Smith55ce3522012-06-25 20:30:08 +00002851/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2852/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2853/// Returns true when the format fits the function and the FormatStringInfo has
2854/// been populated.
2855bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2856 FormatStringInfo *FSI) {
2857 FSI->HasVAListArg = Format->getFirstArg() == 0;
2858 FSI->FormatIdx = Format->getFormatIdx() - 1;
2859 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002860
Richard Smith55ce3522012-06-25 20:30:08 +00002861 // The way the format attribute works in GCC, the implicit this argument
2862 // of member functions is counted. However, it doesn't appear in our own
2863 // lists, so decrement format_idx in that case.
2864 if (IsCXXMember) {
2865 if(FSI->FormatIdx == 0)
2866 return false;
2867 --FSI->FormatIdx;
2868 if (FSI->FirstDataArg != 0)
2869 --FSI->FirstDataArg;
2870 }
2871 return true;
2872}
Mike Stump11289f42009-09-09 15:08:12 +00002873
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002874/// Checks if a the given expression evaluates to null.
2875///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002876/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002877static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002878 // If the expression has non-null type, it doesn't evaluate to null.
2879 if (auto nullability
2880 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2881 if (*nullability == NullabilityKind::NonNull)
2882 return false;
2883 }
2884
Ted Kremeneka146db32014-01-17 06:24:47 +00002885 // As a special case, transparent unions initialized with zero are
2886 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002887 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002888 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2889 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002890 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002891 if (const InitListExpr *ILE =
2892 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002893 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002894 }
2895
2896 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002897 return (!Expr->isValueDependent() &&
2898 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2899 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002900}
2901
2902static void CheckNonNullArgument(Sema &S,
2903 const Expr *ArgExpr,
2904 SourceLocation CallSiteLoc) {
2905 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002906 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2907 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002908}
2909
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002910bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2911 FormatStringInfo FSI;
2912 if ((GetFormatStringType(Format) == FST_NSString) &&
2913 getFormatStringInfo(Format, false, &FSI)) {
2914 Idx = FSI.FormatIdx;
2915 return true;
2916 }
2917 return false;
2918}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002919
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002920/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002921/// as formatting string to formatting method.
2922static void
2923DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2924 const NamedDecl *FDecl,
2925 Expr **Args,
2926 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002927 unsigned Idx = 0;
2928 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002929 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2930 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002931 Idx = 2;
2932 Format = true;
2933 }
2934 else
2935 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2936 if (S.GetFormatNSStringIdx(I, Idx)) {
2937 Format = true;
2938 break;
2939 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002940 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002941 if (!Format || NumArgs <= Idx)
2942 return;
2943 const Expr *FormatExpr = Args[Idx];
2944 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2945 FormatExpr = CSCE->getSubExpr();
2946 const StringLiteral *FormatString;
2947 if (const ObjCStringLiteral *OSL =
2948 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2949 FormatString = OSL->getString();
2950 else
2951 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2952 if (!FormatString)
2953 return;
2954 if (S.FormatStringHasSArg(FormatString)) {
2955 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2956 << "%s" << 1 << 1;
2957 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2958 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002959 }
2960}
2961
Douglas Gregorb4866e82015-06-19 18:13:19 +00002962/// Determine whether the given type has a non-null nullability annotation.
2963static bool isNonNullType(ASTContext &ctx, QualType type) {
2964 if (auto nullability = type->getNullability(ctx))
2965 return *nullability == NullabilityKind::NonNull;
2966
2967 return false;
2968}
2969
Ted Kremenek2bc73332014-01-17 06:24:43 +00002970static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002971 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002972 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002973 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002974 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002975 assert((FDecl || Proto) && "Need a function declaration or prototype");
2976
Ted Kremenek9aedc152014-01-17 06:24:56 +00002977 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002978 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002979 if (FDecl) {
2980 // Handle the nonnull attribute on the function/method declaration itself.
2981 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2982 if (!NonNull->args_size()) {
2983 // Easy case: all pointer arguments are nonnull.
2984 for (const auto *Arg : Args)
2985 if (S.isValidPointerAttrType(Arg->getType()))
2986 CheckNonNullArgument(S, Arg, CallSiteLoc);
2987 return;
2988 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002989
Joel E. Denny81508102018-03-13 14:51:22 +00002990 for (const ParamIdx &Idx : NonNull->args()) {
2991 unsigned IdxAST = Idx.getASTIndex();
2992 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00002993 continue;
2994 if (NonNullArgs.empty())
2995 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00002996 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002997 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002998 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002999 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003000
Douglas Gregorb4866e82015-06-19 18:13:19 +00003001 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3002 // Handle the nonnull attribute on the parameters of the
3003 // function/method.
3004 ArrayRef<ParmVarDecl*> parms;
3005 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3006 parms = FD->parameters();
3007 else
3008 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3009
3010 unsigned ParamIndex = 0;
3011 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3012 I != E; ++I, ++ParamIndex) {
3013 const ParmVarDecl *PVD = *I;
3014 if (PVD->hasAttr<NonNullAttr>() ||
3015 isNonNullType(S.Context, PVD->getType())) {
3016 if (NonNullArgs.empty())
3017 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00003018
Douglas Gregorb4866e82015-06-19 18:13:19 +00003019 NonNullArgs.set(ParamIndex);
3020 }
3021 }
3022 } else {
3023 // If we have a non-function, non-method declaration but no
3024 // function prototype, try to dig out the function prototype.
3025 if (!Proto) {
3026 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3027 QualType type = VD->getType().getNonReferenceType();
3028 if (auto pointerType = type->getAs<PointerType>())
3029 type = pointerType->getPointeeType();
3030 else if (auto blockType = type->getAs<BlockPointerType>())
3031 type = blockType->getPointeeType();
3032 // FIXME: data member pointers?
3033
3034 // Dig out the function prototype, if there is one.
3035 Proto = type->getAs<FunctionProtoType>();
3036 }
3037 }
3038
3039 // Fill in non-null argument information from the nullability
3040 // information on the parameter types (if we have them).
3041 if (Proto) {
3042 unsigned Index = 0;
3043 for (auto paramType : Proto->getParamTypes()) {
3044 if (isNonNullType(S.Context, paramType)) {
3045 if (NonNullArgs.empty())
3046 NonNullArgs.resize(Args.size());
3047
3048 NonNullArgs.set(Index);
3049 }
3050
3051 ++Index;
3052 }
3053 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003054 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003055
Douglas Gregorb4866e82015-06-19 18:13:19 +00003056 // Check for non-null arguments.
3057 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3058 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00003059 if (NonNullArgs[ArgIndex])
3060 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003061 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003062}
3063
Richard Smith55ce3522012-06-25 20:30:08 +00003064/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00003065/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3066/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003067void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00003068 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3069 bool IsMemberFunction, SourceLocation Loc,
3070 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00003071 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00003072 if (CurContext->isDependentContext())
3073 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00003074
Ted Kremenekb8176da2010-09-09 04:33:05 +00003075 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003076 llvm::SmallBitVector CheckedVarArgs;
3077 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003078 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003079 // Only create vector if there are format attributes.
3080 CheckedVarArgs.resize(Args.size());
3081
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003082 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003083 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003084 }
Richard Smithd7293d72013-08-05 18:49:43 +00003085 }
Richard Smith55ce3522012-06-25 20:30:08 +00003086
3087 // Refuse POD arguments that weren't caught by the format string
3088 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003089 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3090 if (CallType != VariadicDoesNotApply &&
3091 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003092 unsigned NumParams = Proto ? Proto->getNumParams()
3093 : FDecl && isa<FunctionDecl>(FDecl)
3094 ? cast<FunctionDecl>(FDecl)->getNumParams()
3095 : FDecl && isa<ObjCMethodDecl>(FDecl)
3096 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3097 : 0;
3098
Alp Toker9cacbab2014-01-20 20:26:09 +00003099 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003100 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003101 if (const Expr *Arg = Args[ArgIdx]) {
3102 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3103 checkVariadicArgument(Arg, CallType);
3104 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003105 }
Richard Smithd7293d72013-08-05 18:49:43 +00003106 }
Mike Stump11289f42009-09-09 15:08:12 +00003107
Douglas Gregorb4866e82015-06-19 18:13:19 +00003108 if (FDecl || Proto) {
3109 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003110
Richard Trieu41bc0992013-06-22 00:20:41 +00003111 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003112 if (FDecl) {
3113 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003114 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003115 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003116 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003117
3118 if (FD)
3119 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003120}
3121
3122/// CheckConstructorCall - Check a constructor call for correctness and safety
3123/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003124void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3125 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003126 const FunctionProtoType *Proto,
3127 SourceLocation Loc) {
3128 VariadicCallType CallType =
3129 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003130 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3131 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003132}
3133
3134/// CheckFunctionCall - Check a direct function call for various correctness
3135/// and safety properties not strictly enforced by the C type system.
3136bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3137 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003138 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3139 isa<CXXMethodDecl>(FDecl);
3140 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3141 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003142 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3143 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003144 Expr** Args = TheCall->getArgs();
3145 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003146
3147 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003148 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003149 // If this is a call to a member operator, hide the first argument
3150 // from checkCall.
3151 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003152 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003153 ++Args;
3154 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003155 } else if (IsMemberFunction)
3156 ImplicitThis =
3157 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3158
3159 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003160 IsMemberFunction, TheCall->getRParenLoc(),
3161 TheCall->getCallee()->getSourceRange(), CallType);
3162
3163 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3164 // None of the checks below are needed for functions that don't have
3165 // simple names (e.g., C++ conversion functions).
3166 if (!FnInfo)
3167 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003168
Richard Trieua7f30b12016-12-06 01:42:28 +00003169 CheckAbsoluteValueFunction(TheCall, FDecl);
3170 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003171
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003172 if (getLangOpts().ObjC1)
3173 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003174
Anna Zaks22122702012-01-17 00:37:07 +00003175 unsigned CMId = FDecl->getMemoryFunctionKind();
3176 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003177 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003178
Anna Zaks201d4892012-01-13 21:52:01 +00003179 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003180 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003181 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003182 else if (CMId == Builtin::BIstrncat)
3183 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003184 else
Anna Zaks22122702012-01-17 00:37:07 +00003185 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003186
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003187 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003188}
3189
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003190bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003191 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003192 VariadicCallType CallType =
3193 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003194
George Burgess IVce6284b2017-01-28 02:19:40 +00003195 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3196 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003197 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003198
3199 return false;
3200}
3201
Richard Trieu664c4c62013-06-20 21:03:13 +00003202bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3203 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003204 QualType Ty;
3205 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003206 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003207 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003208 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003209 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003210 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003211
Douglas Gregorb4866e82015-06-19 18:13:19 +00003212 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3213 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003214 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003215
Richard Trieu664c4c62013-06-20 21:03:13 +00003216 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003217 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003218 CallType = VariadicDoesNotApply;
3219 } else if (Ty->isBlockPointerType()) {
3220 CallType = VariadicBlock;
3221 } else { // Ty->isFunctionPointerType()
3222 CallType = VariadicFunction;
3223 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003224
George Burgess IVce6284b2017-01-28 02:19:40 +00003225 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003226 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3227 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003228 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003229
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003230 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003231}
3232
Richard Trieu41bc0992013-06-22 00:20:41 +00003233/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3234/// such as function pointers returned from functions.
3235bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003236 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003237 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003238 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003239 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003240 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003241 TheCall->getCallee()->getSourceRange(), CallType);
3242
3243 return false;
3244}
3245
Tim Northovere94a34c2014-03-11 10:49:14 +00003246static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003247 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003248 return false;
3249
JF Bastiendda2cb12016-04-18 18:01:49 +00003250 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003251 switch (Op) {
3252 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003253 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003254 llvm_unreachable("There is no ordering argument for an init");
3255
3256 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003257 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003258 case AtomicExpr::AO__atomic_load_n:
3259 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003260 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3261 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003262
3263 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003264 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003265 case AtomicExpr::AO__atomic_store:
3266 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003267 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3268 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3269 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003270
3271 default:
3272 return true;
3273 }
3274}
3275
Richard Smithfeea8832012-04-12 05:08:17 +00003276ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3277 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003278 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3279 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003280
Yaxun Liu39195062017-08-04 18:16:31 +00003281 // All the non-OpenCL operations take one of the following forms.
3282 // The OpenCL operations take the __c11 forms with one extra argument for
3283 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003284 enum {
3285 // C __c11_atomic_init(A *, C)
3286 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003287
Richard Smithfeea8832012-04-12 05:08:17 +00003288 // C __c11_atomic_load(A *, int)
3289 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003290
Richard Smithfeea8832012-04-12 05:08:17 +00003291 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003292 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003293
Eric Fiselier8d662442016-03-30 23:39:56 +00003294 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003295 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003296
Richard Smithfeea8832012-04-12 05:08:17 +00003297 // C __c11_atomic_add(A *, M, int)
3298 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003299
Richard Smithfeea8832012-04-12 05:08:17 +00003300 // C __atomic_exchange_n(A *, CP, int)
3301 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003302
Richard Smithfeea8832012-04-12 05:08:17 +00003303 // void __atomic_exchange(A *, C *, CP, int)
3304 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003305
Richard Smithfeea8832012-04-12 05:08:17 +00003306 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3307 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003308
Richard Smithfeea8832012-04-12 05:08:17 +00003309 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3310 GNUCmpXchg
3311 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003312
Yaxun Liu39195062017-08-04 18:16:31 +00003313 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003314 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3315 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003316 // where:
3317 // C is an appropriate type,
3318 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3319 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3320 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3321 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003322
Yaxun Liu39195062017-08-04 18:16:31 +00003323 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3324 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3325 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003326 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3327 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3328 AtomicExpr::AO__atomic_load,
3329 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003330 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3331 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3332 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3333 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3334 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003335 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3336 Op == AtomicExpr::AO__atomic_store_n ||
3337 Op == AtomicExpr::AO__atomic_exchange_n ||
3338 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3339 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003340 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003341
3342 switch (Op) {
3343 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003344 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003345 Form = Init;
3346 break;
3347
3348 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003349 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003350 case AtomicExpr::AO__atomic_load_n:
3351 Form = Load;
3352 break;
3353
Richard Smithfeea8832012-04-12 05:08:17 +00003354 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003355 Form = LoadCopy;
3356 break;
3357
3358 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003359 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003360 case AtomicExpr::AO__atomic_store:
3361 case AtomicExpr::AO__atomic_store_n:
3362 Form = Copy;
3363 break;
3364
3365 case AtomicExpr::AO__c11_atomic_fetch_add:
3366 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003367 case AtomicExpr::AO__opencl_atomic_fetch_add:
3368 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3369 case AtomicExpr::AO__opencl_atomic_fetch_min:
3370 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003371 case AtomicExpr::AO__atomic_fetch_add:
3372 case AtomicExpr::AO__atomic_fetch_sub:
3373 case AtomicExpr::AO__atomic_add_fetch:
3374 case AtomicExpr::AO__atomic_sub_fetch:
3375 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003376 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003377 case AtomicExpr::AO__c11_atomic_fetch_and:
3378 case AtomicExpr::AO__c11_atomic_fetch_or:
3379 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003380 case AtomicExpr::AO__opencl_atomic_fetch_and:
3381 case AtomicExpr::AO__opencl_atomic_fetch_or:
3382 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003383 case AtomicExpr::AO__atomic_fetch_and:
3384 case AtomicExpr::AO__atomic_fetch_or:
3385 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003386 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003387 case AtomicExpr::AO__atomic_and_fetch:
3388 case AtomicExpr::AO__atomic_or_fetch:
3389 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003390 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003391 Form = Arithmetic;
3392 break;
3393
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003394 case AtomicExpr::AO__atomic_fetch_min:
3395 case AtomicExpr::AO__atomic_fetch_max:
3396 IsMinMax = true;
3397 Form = Arithmetic;
3398 break;
3399
Richard Smithfeea8832012-04-12 05:08:17 +00003400 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003401 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003402 case AtomicExpr::AO__atomic_exchange_n:
3403 Form = Xchg;
3404 break;
3405
3406 case AtomicExpr::AO__atomic_exchange:
3407 Form = GNUXchg;
3408 break;
3409
3410 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3411 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003412 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3413 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003414 Form = C11CmpXchg;
3415 break;
3416
3417 case AtomicExpr::AO__atomic_compare_exchange:
3418 case AtomicExpr::AO__atomic_compare_exchange_n:
3419 Form = GNUCmpXchg;
3420 break;
3421 }
3422
Yaxun Liu39195062017-08-04 18:16:31 +00003423 unsigned AdjustedNumArgs = NumArgs[Form];
3424 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3425 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003426 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003427 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003428 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003429 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003430 << TheCall->getCallee()->getSourceRange();
3431 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003432 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3433 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003434 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003435 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003436 << TheCall->getCallee()->getSourceRange();
3437 return ExprError();
3438 }
3439
Richard Smithfeea8832012-04-12 05:08:17 +00003440 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003441 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003442 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3443 if (ConvertedPtr.isInvalid())
3444 return ExprError();
3445
3446 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003447 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3448 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003449 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003450 << Ptr->getType() << Ptr->getSourceRange();
3451 return ExprError();
3452 }
3453
Richard Smithfeea8832012-04-12 05:08:17 +00003454 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3455 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3456 QualType ValType = AtomTy; // 'C'
3457 if (IsC11) {
3458 if (!AtomTy->isAtomicType()) {
3459 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3460 << Ptr->getType() << Ptr->getSourceRange();
3461 return ExprError();
3462 }
Yaxun Liu39195062017-08-04 18:16:31 +00003463 if (AtomTy.isConstQualified() ||
3464 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003465 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003466 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3467 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003468 return ExprError();
3469 }
Richard Smithfeea8832012-04-12 05:08:17 +00003470 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003471 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003472 if (ValType.isConstQualified()) {
3473 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3474 << Ptr->getType() << Ptr->getSourceRange();
3475 return ExprError();
3476 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003477 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003478
Richard Smithfeea8832012-04-12 05:08:17 +00003479 // For an arithmetic operation, the implied arithmetic must be well-formed.
3480 if (Form == Arithmetic) {
3481 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003482 if (IsAddSub && !ValType->isIntegerType()
3483 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003484 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3485 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3486 return ExprError();
3487 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003488 if (IsMinMax) {
3489 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3490 if (!BT || (BT->getKind() != BuiltinType::Int &&
3491 BT->getKind() != BuiltinType::UInt)) {
3492 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3493 return ExprError();
3494 }
3495 }
3496 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003497 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3498 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3499 return ExprError();
3500 }
David Majnemere85cff82015-01-28 05:48:06 +00003501 if (IsC11 && ValType->isPointerType() &&
3502 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3503 diag::err_incomplete_type)) {
3504 return ExprError();
3505 }
Richard Smithfeea8832012-04-12 05:08:17 +00003506 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3507 // For __atomic_*_n operations, the value type must be a scalar integral or
3508 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003509 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003510 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3511 return ExprError();
3512 }
3513
Eli Friedmanaa769812013-09-11 03:49:34 +00003514 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3515 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003516 // For GNU atomics, require a trivially-copyable type. This is not part of
3517 // the GNU atomics specification, but we enforce it for sanity.
3518 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003519 << Ptr->getType() << Ptr->getSourceRange();
3520 return ExprError();
3521 }
3522
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003523 switch (ValType.getObjCLifetime()) {
3524 case Qualifiers::OCL_None:
3525 case Qualifiers::OCL_ExplicitNone:
3526 // okay
3527 break;
3528
3529 case Qualifiers::OCL_Weak:
3530 case Qualifiers::OCL_Strong:
3531 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003532 // FIXME: Can this happen? By this point, ValType should be known
3533 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003534 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3535 << ValType << Ptr->getSourceRange();
3536 return ExprError();
3537 }
3538
JF Bastien7f0a05a2018-05-25 00:07:09 +00003539 // All atomic operations have an overload which takes a pointer to a volatile
3540 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3541 // into the result or the other operands. Similarly atomic_load takes a
3542 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003543 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003544 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003545 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003546 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3547 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003548 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003549 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003550 ResultType = Context.BoolTy;
3551
Richard Smithfeea8832012-04-12 05:08:17 +00003552 // The type of a parameter passed 'by value'. In the GNU atomics, such
3553 // arguments are actually passed as pointers.
3554 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003555 bool IsPassedByAddress = false;
3556 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003557 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003558 IsPassedByAddress = true;
3559 }
Richard Smithfeea8832012-04-12 05:08:17 +00003560
JF Bastien7f0a05a2018-05-25 00:07:09 +00003561 // The first argument's non-CV pointer type is used to deduce the type of
3562 // subsequent arguments, except for:
3563 // - weak flag (always converted to bool)
3564 // - memory order (always converted to int)
3565 // - scope (always converted to int)
3566 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003567 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003568 if (i < NumVals[Form] + 1) {
3569 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003570 case 0:
3571 // The first argument is always a pointer. It has a fixed type.
3572 // It is always dereferenced, a nullptr is undefined.
3573 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3574 // Nothing else to do: we already know all we want about this pointer.
3575 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003576 case 1:
3577 // The second argument is the non-atomic operand. For arithmetic, this
3578 // is always passed by value, and for a compare_exchange it is always
3579 // passed by address. For the rest, GNU uses by-address and C11 uses
3580 // by-value.
3581 assert(Form != Load);
3582 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3583 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003584 else if (Form == Copy || Form == Xchg) {
3585 if (IsPassedByAddress)
3586 // The value pointer is always dereferenced, a nullptr is undefined.
3587 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003588 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003589 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003590 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003591 else {
3592 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003593 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003594 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003595 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003596 // Keep address space of non-atomic pointer type.
3597 if (const PointerType *PtrTy =
3598 ValArg->getType()->getAs<PointerType>()) {
3599 AS = PtrTy->getPointeeType().getAddressSpace();
3600 }
3601 Ty = Context.getPointerType(
3602 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3603 }
Richard Smithfeea8832012-04-12 05:08:17 +00003604 break;
3605 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003606 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003607 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3608 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003609 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003610 Ty = ByValType;
3611 break;
3612 case 3:
3613 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3614 Ty = Context.BoolTy;
3615 break;
3616 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003617 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003618 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003619 Ty = Context.IntTy;
3620 }
Richard Smithfeea8832012-04-12 05:08:17 +00003621
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003622 InitializedEntity Entity =
3623 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003624 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003625 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3626 if (Arg.isInvalid())
3627 return true;
3628 TheCall->setArg(i, Arg.get());
3629 }
3630
Richard Smithfeea8832012-04-12 05:08:17 +00003631 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003632 SmallVector<Expr*, 5> SubExprs;
3633 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003634 switch (Form) {
3635 case Init:
3636 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003637 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003638 break;
3639 case Load:
3640 SubExprs.push_back(TheCall->getArg(1)); // Order
3641 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003642 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003643 case Copy:
3644 case Arithmetic:
3645 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003646 SubExprs.push_back(TheCall->getArg(2)); // Order
3647 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003648 break;
3649 case GNUXchg:
3650 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3651 SubExprs.push_back(TheCall->getArg(3)); // Order
3652 SubExprs.push_back(TheCall->getArg(1)); // Val1
3653 SubExprs.push_back(TheCall->getArg(2)); // Val2
3654 break;
3655 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003656 SubExprs.push_back(TheCall->getArg(3)); // Order
3657 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003658 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003659 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003660 break;
3661 case GNUCmpXchg:
3662 SubExprs.push_back(TheCall->getArg(4)); // Order
3663 SubExprs.push_back(TheCall->getArg(1)); // Val1
3664 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3665 SubExprs.push_back(TheCall->getArg(2)); // Val2
3666 SubExprs.push_back(TheCall->getArg(3)); // Weak
3667 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003668 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003669
3670 if (SubExprs.size() >= 2 && Form != Init) {
3671 llvm::APSInt Result(32);
3672 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3673 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003674 Diag(SubExprs[1]->getLocStart(),
3675 diag::warn_atomic_op_has_invalid_memory_order)
3676 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003677 }
3678
Yaxun Liu30d652a2017-08-15 16:02:49 +00003679 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3680 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3681 llvm::APSInt Result(32);
3682 if (Scope->isIntegerConstantExpr(Result, Context) &&
3683 !ScopeModel->isValid(Result.getZExtValue())) {
3684 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3685 << Scope->getSourceRange();
3686 }
3687 SubExprs.push_back(Scope);
3688 }
3689
Fariborz Jahanian615de762013-05-28 17:37:39 +00003690 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3691 SubExprs, ResultType, Op,
3692 TheCall->getRParenLoc());
3693
3694 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003695 Op == AtomicExpr::AO__c11_atomic_store ||
3696 Op == AtomicExpr::AO__opencl_atomic_load ||
3697 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003698 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003699 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3700 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3701 Op == AtomicExpr::AO__opencl_atomic_load)
3702 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003703
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003704 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003705}
3706
John McCall29ad95b2011-08-27 01:09:30 +00003707/// checkBuiltinArgument - Given a call to a builtin function, perform
3708/// normal type-checking on the given argument, updating the call in
3709/// place. This is useful when a builtin function requires custom
3710/// type-checking for some of its arguments but not necessarily all of
3711/// them.
3712///
3713/// Returns true on error.
3714static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3715 FunctionDecl *Fn = E->getDirectCallee();
3716 assert(Fn && "builtin call without direct callee!");
3717
3718 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3719 InitializedEntity Entity =
3720 InitializedEntity::InitializeParameter(S.Context, Param);
3721
3722 ExprResult Arg = E->getArg(0);
3723 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3724 if (Arg.isInvalid())
3725 return true;
3726
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003727 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003728 return false;
3729}
3730
Chris Lattnerdc046542009-05-08 06:58:22 +00003731/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3732/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3733/// type of its first argument. The main ActOnCallExpr routines have already
3734/// promoted the types of arguments because all of these calls are prototyped as
3735/// void(...).
3736///
3737/// This function goes through and does final semantic checking for these
3738/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003739ExprResult
3740Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003741 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003742 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3743 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3744
3745 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003746 if (TheCall->getNumArgs() < 1) {
3747 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3748 << 0 << 1 << TheCall->getNumArgs()
3749 << TheCall->getCallee()->getSourceRange();
3750 return ExprError();
3751 }
Mike Stump11289f42009-09-09 15:08:12 +00003752
Chris Lattnerdc046542009-05-08 06:58:22 +00003753 // Inspect the first argument of the atomic builtin. This should always be
3754 // a pointer type, whose element is an integral scalar or pointer type.
3755 // Because it is a pointer type, we don't have to worry about any implicit
3756 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003757 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003758 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003759 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3760 if (FirstArgResult.isInvalid())
3761 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003762 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003763 TheCall->setArg(0, FirstArg);
3764
John McCall31168b02011-06-15 23:02:42 +00003765 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3766 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003767 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3768 << FirstArg->getType() << FirstArg->getSourceRange();
3769 return ExprError();
3770 }
Mike Stump11289f42009-09-09 15:08:12 +00003771
John McCall31168b02011-06-15 23:02:42 +00003772 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003773 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003774 !ValType->isBlockPointerType()) {
3775 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3776 << FirstArg->getType() << FirstArg->getSourceRange();
3777 return ExprError();
3778 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003779
Aaron Ballmana383c942018-05-05 17:38:42 +00003780 if (ValType.isConstQualified()) {
3781 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3782 << FirstArg->getType() << FirstArg->getSourceRange();
3783 return ExprError();
3784 }
3785
John McCall31168b02011-06-15 23:02:42 +00003786 switch (ValType.getObjCLifetime()) {
3787 case Qualifiers::OCL_None:
3788 case Qualifiers::OCL_ExplicitNone:
3789 // okay
3790 break;
3791
3792 case Qualifiers::OCL_Weak:
3793 case Qualifiers::OCL_Strong:
3794 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003795 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003796 << ValType << FirstArg->getSourceRange();
3797 return ExprError();
3798 }
3799
John McCallb50451a2011-10-05 07:41:44 +00003800 // Strip any qualifiers off ValType.
3801 ValType = ValType.getUnqualifiedType();
3802
Chandler Carruth3973af72010-07-18 20:54:12 +00003803 // The majority of builtins return a value, but a few have special return
3804 // types, so allow them to override appropriately below.
3805 QualType ResultType = ValType;
3806
Chris Lattnerdc046542009-05-08 06:58:22 +00003807 // We need to figure out which concrete builtin this maps onto. For example,
3808 // __sync_fetch_and_add with a 2 byte object turns into
3809 // __sync_fetch_and_add_2.
3810#define BUILTIN_ROW(x) \
3811 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3812 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003813
Chris Lattnerdc046542009-05-08 06:58:22 +00003814 static const unsigned BuiltinIndices[][5] = {
3815 BUILTIN_ROW(__sync_fetch_and_add),
3816 BUILTIN_ROW(__sync_fetch_and_sub),
3817 BUILTIN_ROW(__sync_fetch_and_or),
3818 BUILTIN_ROW(__sync_fetch_and_and),
3819 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003820 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003821
Chris Lattnerdc046542009-05-08 06:58:22 +00003822 BUILTIN_ROW(__sync_add_and_fetch),
3823 BUILTIN_ROW(__sync_sub_and_fetch),
3824 BUILTIN_ROW(__sync_and_and_fetch),
3825 BUILTIN_ROW(__sync_or_and_fetch),
3826 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003827 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003828
Chris Lattnerdc046542009-05-08 06:58:22 +00003829 BUILTIN_ROW(__sync_val_compare_and_swap),
3830 BUILTIN_ROW(__sync_bool_compare_and_swap),
3831 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003832 BUILTIN_ROW(__sync_lock_release),
3833 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003834 };
Mike Stump11289f42009-09-09 15:08:12 +00003835#undef BUILTIN_ROW
3836
Chris Lattnerdc046542009-05-08 06:58:22 +00003837 // Determine the index of the size.
3838 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003839 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003840 case 1: SizeIndex = 0; break;
3841 case 2: SizeIndex = 1; break;
3842 case 4: SizeIndex = 2; break;
3843 case 8: SizeIndex = 3; break;
3844 case 16: SizeIndex = 4; break;
3845 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003846 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3847 << FirstArg->getType() << FirstArg->getSourceRange();
3848 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003849 }
Mike Stump11289f42009-09-09 15:08:12 +00003850
Chris Lattnerdc046542009-05-08 06:58:22 +00003851 // Each of these builtins has one pointer argument, followed by some number of
3852 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3853 // that we ignore. Find out which row of BuiltinIndices to read from as well
3854 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003855 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003856 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003857 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003858 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003859 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003860 case Builtin::BI__sync_fetch_and_add:
3861 case Builtin::BI__sync_fetch_and_add_1:
3862 case Builtin::BI__sync_fetch_and_add_2:
3863 case Builtin::BI__sync_fetch_and_add_4:
3864 case Builtin::BI__sync_fetch_and_add_8:
3865 case Builtin::BI__sync_fetch_and_add_16:
3866 BuiltinIndex = 0;
3867 break;
3868
3869 case Builtin::BI__sync_fetch_and_sub:
3870 case Builtin::BI__sync_fetch_and_sub_1:
3871 case Builtin::BI__sync_fetch_and_sub_2:
3872 case Builtin::BI__sync_fetch_and_sub_4:
3873 case Builtin::BI__sync_fetch_and_sub_8:
3874 case Builtin::BI__sync_fetch_and_sub_16:
3875 BuiltinIndex = 1;
3876 break;
3877
3878 case Builtin::BI__sync_fetch_and_or:
3879 case Builtin::BI__sync_fetch_and_or_1:
3880 case Builtin::BI__sync_fetch_and_or_2:
3881 case Builtin::BI__sync_fetch_and_or_4:
3882 case Builtin::BI__sync_fetch_and_or_8:
3883 case Builtin::BI__sync_fetch_and_or_16:
3884 BuiltinIndex = 2;
3885 break;
3886
3887 case Builtin::BI__sync_fetch_and_and:
3888 case Builtin::BI__sync_fetch_and_and_1:
3889 case Builtin::BI__sync_fetch_and_and_2:
3890 case Builtin::BI__sync_fetch_and_and_4:
3891 case Builtin::BI__sync_fetch_and_and_8:
3892 case Builtin::BI__sync_fetch_and_and_16:
3893 BuiltinIndex = 3;
3894 break;
Mike Stump11289f42009-09-09 15:08:12 +00003895
Douglas Gregor73722482011-11-28 16:30:08 +00003896 case Builtin::BI__sync_fetch_and_xor:
3897 case Builtin::BI__sync_fetch_and_xor_1:
3898 case Builtin::BI__sync_fetch_and_xor_2:
3899 case Builtin::BI__sync_fetch_and_xor_4:
3900 case Builtin::BI__sync_fetch_and_xor_8:
3901 case Builtin::BI__sync_fetch_and_xor_16:
3902 BuiltinIndex = 4;
3903 break;
3904
Hal Finkeld2208b52014-10-02 20:53:50 +00003905 case Builtin::BI__sync_fetch_and_nand:
3906 case Builtin::BI__sync_fetch_and_nand_1:
3907 case Builtin::BI__sync_fetch_and_nand_2:
3908 case Builtin::BI__sync_fetch_and_nand_4:
3909 case Builtin::BI__sync_fetch_and_nand_8:
3910 case Builtin::BI__sync_fetch_and_nand_16:
3911 BuiltinIndex = 5;
3912 WarnAboutSemanticsChange = true;
3913 break;
3914
Douglas Gregor73722482011-11-28 16:30:08 +00003915 case Builtin::BI__sync_add_and_fetch:
3916 case Builtin::BI__sync_add_and_fetch_1:
3917 case Builtin::BI__sync_add_and_fetch_2:
3918 case Builtin::BI__sync_add_and_fetch_4:
3919 case Builtin::BI__sync_add_and_fetch_8:
3920 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003921 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003922 break;
3923
3924 case Builtin::BI__sync_sub_and_fetch:
3925 case Builtin::BI__sync_sub_and_fetch_1:
3926 case Builtin::BI__sync_sub_and_fetch_2:
3927 case Builtin::BI__sync_sub_and_fetch_4:
3928 case Builtin::BI__sync_sub_and_fetch_8:
3929 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003930 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003931 break;
3932
3933 case Builtin::BI__sync_and_and_fetch:
3934 case Builtin::BI__sync_and_and_fetch_1:
3935 case Builtin::BI__sync_and_and_fetch_2:
3936 case Builtin::BI__sync_and_and_fetch_4:
3937 case Builtin::BI__sync_and_and_fetch_8:
3938 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003939 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003940 break;
3941
3942 case Builtin::BI__sync_or_and_fetch:
3943 case Builtin::BI__sync_or_and_fetch_1:
3944 case Builtin::BI__sync_or_and_fetch_2:
3945 case Builtin::BI__sync_or_and_fetch_4:
3946 case Builtin::BI__sync_or_and_fetch_8:
3947 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003948 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003949 break;
3950
3951 case Builtin::BI__sync_xor_and_fetch:
3952 case Builtin::BI__sync_xor_and_fetch_1:
3953 case Builtin::BI__sync_xor_and_fetch_2:
3954 case Builtin::BI__sync_xor_and_fetch_4:
3955 case Builtin::BI__sync_xor_and_fetch_8:
3956 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003957 BuiltinIndex = 10;
3958 break;
3959
3960 case Builtin::BI__sync_nand_and_fetch:
3961 case Builtin::BI__sync_nand_and_fetch_1:
3962 case Builtin::BI__sync_nand_and_fetch_2:
3963 case Builtin::BI__sync_nand_and_fetch_4:
3964 case Builtin::BI__sync_nand_and_fetch_8:
3965 case Builtin::BI__sync_nand_and_fetch_16:
3966 BuiltinIndex = 11;
3967 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003968 break;
Mike Stump11289f42009-09-09 15:08:12 +00003969
Chris Lattnerdc046542009-05-08 06:58:22 +00003970 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003971 case Builtin::BI__sync_val_compare_and_swap_1:
3972 case Builtin::BI__sync_val_compare_and_swap_2:
3973 case Builtin::BI__sync_val_compare_and_swap_4:
3974 case Builtin::BI__sync_val_compare_and_swap_8:
3975 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003976 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003977 NumFixed = 2;
3978 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003979
Chris Lattnerdc046542009-05-08 06:58:22 +00003980 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003981 case Builtin::BI__sync_bool_compare_and_swap_1:
3982 case Builtin::BI__sync_bool_compare_and_swap_2:
3983 case Builtin::BI__sync_bool_compare_and_swap_4:
3984 case Builtin::BI__sync_bool_compare_and_swap_8:
3985 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003986 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003987 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003988 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003989 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003990
JF Bastien7f0a05a2018-05-25 00:07:09 +00003991 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00003992 case Builtin::BI__sync_lock_test_and_set_1:
3993 case Builtin::BI__sync_lock_test_and_set_2:
3994 case Builtin::BI__sync_lock_test_and_set_4:
3995 case Builtin::BI__sync_lock_test_and_set_8:
3996 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003997 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003998 break;
3999
Chris Lattnerdc046542009-05-08 06:58:22 +00004000 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00004001 case Builtin::BI__sync_lock_release_1:
4002 case Builtin::BI__sync_lock_release_2:
4003 case Builtin::BI__sync_lock_release_4:
4004 case Builtin::BI__sync_lock_release_8:
4005 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004006 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00004007 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00004008 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004009 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004010
4011 case Builtin::BI__sync_swap:
4012 case Builtin::BI__sync_swap_1:
4013 case Builtin::BI__sync_swap_2:
4014 case Builtin::BI__sync_swap_4:
4015 case Builtin::BI__sync_swap_8:
4016 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004017 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00004018 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00004019 }
Mike Stump11289f42009-09-09 15:08:12 +00004020
Chris Lattnerdc046542009-05-08 06:58:22 +00004021 // Now that we know how many fixed arguments we expect, first check that we
4022 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004023 if (TheCall->getNumArgs() < 1+NumFixed) {
4024 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4025 << 0 << 1+NumFixed << TheCall->getNumArgs()
4026 << TheCall->getCallee()->getSourceRange();
4027 return ExprError();
4028 }
Mike Stump11289f42009-09-09 15:08:12 +00004029
Hal Finkeld2208b52014-10-02 20:53:50 +00004030 if (WarnAboutSemanticsChange) {
4031 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4032 << TheCall->getCallee()->getSourceRange();
4033 }
4034
Chris Lattner5b9241b2009-05-08 15:36:58 +00004035 // Get the decl for the concrete builtin from this, we can tell what the
4036 // concrete integer type we should convert to is.
4037 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00004038 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004039 FunctionDecl *NewBuiltinDecl;
4040 if (NewBuiltinID == BuiltinID)
4041 NewBuiltinDecl = FDecl;
4042 else {
4043 // Perform builtin lookup to avoid redeclaring it.
4044 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4045 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4046 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4047 assert(Res.getFoundDecl());
4048 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004049 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004050 return ExprError();
4051 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004052
John McCallcf142162010-08-07 06:22:56 +00004053 // The first argument --- the pointer --- has a fixed type; we
4054 // deduce the types of the rest of the arguments accordingly. Walk
4055 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00004056 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004057 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00004058
Chris Lattnerdc046542009-05-08 06:58:22 +00004059 // GCC does an implicit conversion to the pointer or integer ValType. This
4060 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00004061 // Initialize the argument.
4062 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4063 ValType, /*consume*/ false);
4064 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00004065 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004066 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004067
Chris Lattnerdc046542009-05-08 06:58:22 +00004068 // Okay, we have something that *can* be converted to the right type. Check
4069 // to see if there is a potentially weird extension going on here. This can
4070 // happen when you do an atomic operation on something like an char* and
4071 // pass in 42. The 42 gets converted to char. This is even more strange
4072 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00004073 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004074 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004075 }
Mike Stump11289f42009-09-09 15:08:12 +00004076
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004077 ASTContext& Context = this->getASTContext();
4078
4079 // Create a new DeclRefExpr to refer to the new decl.
4080 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4081 Context,
4082 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004083 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004084 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004085 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004086 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004087 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004088 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004089
Chris Lattnerdc046542009-05-08 06:58:22 +00004090 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004091 // FIXME: This loses syntactic information.
4092 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4093 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4094 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004095 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004096
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004097 // Change the result type of the call to match the original value type. This
4098 // is arbitrary, but the codegen for these builtins ins design to handle it
4099 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004100 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004101
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004102 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004103}
4104
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004105/// SemaBuiltinNontemporalOverloaded - We have a call to
4106/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4107/// overloaded function based on the pointer type of its last argument.
4108///
4109/// This function goes through and does final semantic checking for these
4110/// builtins.
4111ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4112 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4113 DeclRefExpr *DRE =
4114 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4115 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4116 unsigned BuiltinID = FDecl->getBuiltinID();
4117 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4118 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4119 "Unexpected nontemporal load/store builtin!");
4120 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4121 unsigned numArgs = isStore ? 2 : 1;
4122
4123 // Ensure that we have the proper number of arguments.
4124 if (checkArgCount(*this, TheCall, numArgs))
4125 return ExprError();
4126
4127 // Inspect the last argument of the nontemporal builtin. This should always
4128 // be a pointer type, from which we imply the type of the memory access.
4129 // Because it is a pointer type, we don't have to worry about any implicit
4130 // casts here.
4131 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4132 ExprResult PointerArgResult =
4133 DefaultFunctionArrayLvalueConversion(PointerArg);
4134
4135 if (PointerArgResult.isInvalid())
4136 return ExprError();
4137 PointerArg = PointerArgResult.get();
4138 TheCall->setArg(numArgs - 1, PointerArg);
4139
4140 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4141 if (!pointerType) {
4142 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4143 << PointerArg->getType() << PointerArg->getSourceRange();
4144 return ExprError();
4145 }
4146
4147 QualType ValType = pointerType->getPointeeType();
4148
4149 // Strip any qualifiers off ValType.
4150 ValType = ValType.getUnqualifiedType();
4151 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4152 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4153 !ValType->isVectorType()) {
4154 Diag(DRE->getLocStart(),
4155 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4156 << PointerArg->getType() << PointerArg->getSourceRange();
4157 return ExprError();
4158 }
4159
4160 if (!isStore) {
4161 TheCall->setType(ValType);
4162 return TheCallResult;
4163 }
4164
4165 ExprResult ValArg = TheCall->getArg(0);
4166 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4167 Context, ValType, /*consume*/ false);
4168 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4169 if (ValArg.isInvalid())
4170 return ExprError();
4171
4172 TheCall->setArg(0, ValArg.get());
4173 TheCall->setType(Context.VoidTy);
4174 return TheCallResult;
4175}
4176
Chris Lattner6436fb62009-02-18 06:01:06 +00004177/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004178/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004179/// Note: It might also make sense to do the UTF-16 conversion here (would
4180/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004181bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004182 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004183 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4184
Douglas Gregorfb65e592011-07-27 05:40:30 +00004185 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004186 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4187 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004188 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004189 }
Mike Stump11289f42009-09-09 15:08:12 +00004190
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004191 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004192 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004193 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004194 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4195 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4196 llvm::UTF16 *ToPtr = &ToBuf[0];
4197
4198 llvm::ConversionResult Result =
4199 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4200 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004201 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004202 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004203 Diag(Arg->getLocStart(),
4204 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4205 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004206 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004207}
4208
Mehdi Amini06d367c2016-10-24 20:39:34 +00004209/// CheckObjCString - Checks that the format string argument to the os_log()
4210/// and os_trace() functions is correct, and converts it to const char *.
4211ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4212 Arg = Arg->IgnoreParenCasts();
4213 auto *Literal = dyn_cast<StringLiteral>(Arg);
4214 if (!Literal) {
4215 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4216 Literal = ObjcLiteral->getString();
4217 }
4218 }
4219
4220 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4221 return ExprError(
4222 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4223 << Arg->getSourceRange());
4224 }
4225
4226 ExprResult Result(Literal);
4227 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4228 InitializedEntity Entity =
4229 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4230 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4231 return Result;
4232}
4233
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004234/// Check that the user is calling the appropriate va_start builtin for the
4235/// target and calling convention.
4236static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4237 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4238 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004239 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004240 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004241 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4242 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004243 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004244 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4245 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4246 if (IsMSVAStart) {
4247 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004248 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004249 return S.Diag(Fn->getLocStart(),
4250 diag::err_ms_va_start_used_in_sysv_function);
4251 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004252 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004253 // On x64 Windows, don't allow this in System V ABI functions.
4254 // (Yes, that means there's no corresponding way to support variadic
4255 // System V ABI functions on Windows.)
4256 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004257 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004258 return S.Diag(Fn->getLocStart(),
4259 diag::err_va_start_used_in_wrong_abi_function)
4260 << !IsWindows;
4261 }
4262 return false;
4263 }
4264
4265 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004266 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004267 return false;
4268}
4269
4270static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4271 ParmVarDecl **LastParam = nullptr) {
4272 // Determine whether the current function, block, or obj-c method is variadic
4273 // and get its parameter list.
4274 bool IsVariadic = false;
4275 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004276 DeclContext *Caller = S.CurContext;
4277 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4278 IsVariadic = Block->isVariadic();
4279 Params = Block->parameters();
4280 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004281 IsVariadic = FD->isVariadic();
4282 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004283 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004284 IsVariadic = MD->isVariadic();
4285 // FIXME: This isn't correct for methods (results in bogus warning).
4286 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004287 } else if (isa<CapturedDecl>(Caller)) {
4288 // We don't support va_start in a CapturedDecl.
4289 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4290 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004291 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004292 // This must be some other declcontext that parses exprs.
4293 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4294 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004295 }
4296
4297 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004298 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004299 return true;
4300 }
4301
4302 if (LastParam)
4303 *LastParam = Params.empty() ? nullptr : Params.back();
4304
4305 return false;
4306}
4307
Charles Davisc7d5c942015-09-17 20:55:33 +00004308/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4309/// for validity. Emit an error and return true on failure; return false
4310/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004311bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00004312 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004313
4314 if (checkVAStartABI(*this, BuiltinID, Fn))
4315 return true;
4316
Chris Lattner08464942007-12-28 05:29:59 +00004317 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00004318 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004319 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004320 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4321 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00004322 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004323 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00004324 return true;
4325 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004326
4327 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00004328 return Diag(TheCall->getLocEnd(),
4329 diag::err_typecheck_call_too_few_args_at_least)
4330 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004331 }
4332
John McCall29ad95b2011-08-27 01:09:30 +00004333 // Type-check the first argument normally.
4334 if (checkBuiltinArgument(*this, TheCall, 0))
4335 return true;
4336
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004337 // Check that the current function is variadic, and get its last parameter.
4338 ParmVarDecl *LastParam;
4339 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004340 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004341
Chris Lattner43be2e62007-12-19 23:59:04 +00004342 // Verify that the second argument to the builtin is the last argument of the
4343 // current function or method.
4344 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004345 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004346
Nico Weber9eea7642013-05-24 23:31:57 +00004347 // These are valid if SecondArgIsLastNamedArgument is false after the next
4348 // block.
4349 QualType Type;
4350 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004351 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004352
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004353 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4354 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004355 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004356
4357 Type = PV->getType();
4358 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004359 IsCRegister =
4360 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004361 }
4362 }
Mike Stump11289f42009-09-09 15:08:12 +00004363
Chris Lattner43be2e62007-12-19 23:59:04 +00004364 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004365 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004366 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004367 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004368 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4369 // Promotable integers are UB, but enumerations need a bit of
4370 // extra checking to see what their promotable type actually is.
4371 if (!Type->isPromotableIntegerType())
4372 return false;
4373 if (!Type->isEnumeralType())
4374 return true;
4375 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4376 return !(ED &&
4377 Context.typesAreCompatible(ED->getPromotionType(), Type));
4378 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004379 unsigned Reason = 0;
4380 if (Type->isReferenceType()) Reason = 1;
4381 else if (IsCRegister) Reason = 2;
4382 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004383 Diag(ParamLoc, diag::note_parameter_type) << Type;
4384 }
4385
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004386 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004387 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004388}
Chris Lattner43be2e62007-12-19 23:59:04 +00004389
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004390bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004391 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4392 // const char *named_addr);
4393
4394 Expr *Func = Call->getCallee();
4395
4396 if (Call->getNumArgs() < 3)
4397 return Diag(Call->getLocEnd(),
4398 diag::err_typecheck_call_too_few_args_at_least)
4399 << 0 /*function call*/ << 3 << Call->getNumArgs();
4400
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004401 // Type-check the first argument normally.
4402 if (checkBuiltinArgument(*this, Call, 0))
4403 return true;
4404
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004405 // Check that the current function is variadic.
4406 if (checkVAStartIsInVariadicFunction(*this, Func))
4407 return true;
4408
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004409 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004410
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004411 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4412 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4413
4414 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4415 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4416
4417 const QualType &ConstCharPtrTy =
4418 Context.getPointerType(Context.CharTy.withConst());
4419 if (!Arg1Ty->isPointerType() ||
4420 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4421 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4422 << Arg1->getType() << ConstCharPtrTy
4423 << 1 /* different class */
4424 << 0 /* qualifier difference */
4425 << 3 /* parameter mismatch */
4426 << 2 << Arg1->getType() << ConstCharPtrTy;
4427
4428 const QualType SizeTy = Context.getSizeType();
4429 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4430 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4431 << Arg2->getType() << SizeTy
4432 << 1 /* different class */
4433 << 0 /* qualifier difference */
4434 << 3 /* parameter mismatch */
4435 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004436
4437 return false;
4438}
4439
Chris Lattner2da14fb2007-12-20 00:26:33 +00004440/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4441/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004442bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4443 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004444 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004445 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004446 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004447 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004448 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004449 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004450 << SourceRange(TheCall->getArg(2)->getLocStart(),
4451 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004452
John Wiegley01296292011-04-08 18:41:53 +00004453 ExprResult OrigArg0 = TheCall->getArg(0);
4454 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004455
Chris Lattner2da14fb2007-12-20 00:26:33 +00004456 // Do standard promotions between the two arguments, returning their common
4457 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004458 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004459 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4460 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004461
4462 // Make sure any conversions are pushed back into the call; this is
4463 // type safe since unordered compare builtins are declared as "_Bool
4464 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004465 TheCall->setArg(0, OrigArg0.get());
4466 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004467
John Wiegley01296292011-04-08 18:41:53 +00004468 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004469 return false;
4470
Chris Lattner2da14fb2007-12-20 00:26:33 +00004471 // If the common type isn't a real floating type, then the arguments were
4472 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004473 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004474 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004475 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004476 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4477 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004478
Chris Lattner2da14fb2007-12-20 00:26:33 +00004479 return false;
4480}
4481
Benjamin Kramer634fc102010-02-15 22:42:31 +00004482/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4483/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004484/// to check everything. We expect the last argument to be a floating point
4485/// value.
4486bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4487 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004488 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004489 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004490 if (TheCall->getNumArgs() > NumArgs)
4491 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004492 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004493 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004494 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004495 (*(TheCall->arg_end()-1))->getLocEnd());
4496
Benjamin Kramer64aae502010-02-16 10:07:31 +00004497 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004498
Eli Friedman7e4faac2009-08-31 20:06:00 +00004499 if (OrigArg->isTypeDependent())
4500 return false;
4501
Chris Lattner68784ef2010-05-06 05:50:07 +00004502 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004503 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004504 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004505 diag::err_typecheck_call_invalid_unary_fp)
4506 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004507
Neil Hickey88c0fac2016-12-13 16:22:50 +00004508 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004509 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004510 // Only remove standard FloatCasts, leaving other casts inplace
4511 if (Cast->getCastKind() == CK_FloatingCast) {
4512 Expr *CastArg = Cast->getSubExpr();
4513 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4514 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4515 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4516 "promotion from float to either float or double is the only expected cast here");
4517 Cast->setSubExpr(nullptr);
4518 TheCall->setArg(NumArgs-1, CastArg);
4519 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004520 }
4521 }
4522
Eli Friedman7e4faac2009-08-31 20:06:00 +00004523 return false;
4524}
4525
Tony Jiangbbc48e92017-05-24 15:13:32 +00004526// Customized Sema Checking for VSX builtins that have the following signature:
4527// vector [...] builtinName(vector [...], vector [...], const int);
4528// Which takes the same type of vectors (any legal vector type) for the first
4529// two arguments and takes compile time constant for the third argument.
4530// Example builtins are :
4531// vector double vec_xxpermdi(vector double, vector double, int);
4532// vector short vec_xxsldwi(vector short, vector short, int);
4533bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4534 unsigned ExpectedNumArgs = 3;
4535 if (TheCall->getNumArgs() < ExpectedNumArgs)
4536 return Diag(TheCall->getLocEnd(),
4537 diag::err_typecheck_call_too_few_args_at_least)
4538 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4539 << TheCall->getSourceRange();
4540
4541 if (TheCall->getNumArgs() > ExpectedNumArgs)
4542 return Diag(TheCall->getLocEnd(),
4543 diag::err_typecheck_call_too_many_args_at_most)
4544 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4545 << TheCall->getSourceRange();
4546
4547 // Check the third argument is a compile time constant
4548 llvm::APSInt Value;
4549 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4550 return Diag(TheCall->getLocStart(),
4551 diag::err_vsx_builtin_nonconstant_argument)
4552 << 3 /* argument index */ << TheCall->getDirectCallee()
4553 << SourceRange(TheCall->getArg(2)->getLocStart(),
4554 TheCall->getArg(2)->getLocEnd());
4555
4556 QualType Arg1Ty = TheCall->getArg(0)->getType();
4557 QualType Arg2Ty = TheCall->getArg(1)->getType();
4558
4559 // Check the type of argument 1 and argument 2 are vectors.
4560 SourceLocation BuiltinLoc = TheCall->getLocStart();
4561 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4562 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4563 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4564 << TheCall->getDirectCallee()
4565 << SourceRange(TheCall->getArg(0)->getLocStart(),
4566 TheCall->getArg(1)->getLocEnd());
4567 }
4568
4569 // Check the first two arguments are the same type.
4570 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4571 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4572 << TheCall->getDirectCallee()
4573 << SourceRange(TheCall->getArg(0)->getLocStart(),
4574 TheCall->getArg(1)->getLocEnd());
4575 }
4576
4577 // When default clang type checking is turned off and the customized type
4578 // checking is used, the returning type of the function must be explicitly
4579 // set. Otherwise it is _Bool by default.
4580 TheCall->setType(Arg1Ty);
4581
4582 return false;
4583}
4584
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004585/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4586// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004587ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004588 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004589 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004590 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004591 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4592 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004593
Nate Begemana0110022010-06-08 00:16:34 +00004594 // Determine which of the following types of shufflevector we're checking:
4595 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004596 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004597 QualType resType = TheCall->getArg(0)->getType();
4598 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004599
Douglas Gregorc25f7662009-05-19 22:10:17 +00004600 if (!TheCall->getArg(0)->isTypeDependent() &&
4601 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004602 QualType LHSType = TheCall->getArg(0)->getType();
4603 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004604
Craig Topperbaca3892013-07-29 06:47:04 +00004605 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4606 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004607 diag::err_vec_builtin_non_vector)
4608 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004609 << SourceRange(TheCall->getArg(0)->getLocStart(),
4610 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004611
Nate Begemana0110022010-06-08 00:16:34 +00004612 numElements = LHSType->getAs<VectorType>()->getNumElements();
4613 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004614
Nate Begemana0110022010-06-08 00:16:34 +00004615 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4616 // with mask. If so, verify that RHS is an integer vector type with the
4617 // same number of elts as lhs.
4618 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004619 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004620 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004621 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004622 diag::err_vec_builtin_incompatible_vector)
4623 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004624 << SourceRange(TheCall->getArg(1)->getLocStart(),
4625 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004626 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004627 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004628 diag::err_vec_builtin_incompatible_vector)
4629 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004630 << SourceRange(TheCall->getArg(0)->getLocStart(),
4631 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004632 } else if (numElements != numResElements) {
4633 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004634 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004635 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004636 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004637 }
4638
4639 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004640 if (TheCall->getArg(i)->isTypeDependent() ||
4641 TheCall->getArg(i)->isValueDependent())
4642 continue;
4643
Nate Begemana0110022010-06-08 00:16:34 +00004644 llvm::APSInt Result(32);
4645 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4646 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004647 diag::err_shufflevector_nonconstant_argument)
4648 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004649
Craig Topper50ad5b72013-08-03 17:40:38 +00004650 // Allow -1 which will be translated to undef in the IR.
4651 if (Result.isSigned() && Result.isAllOnesValue())
4652 continue;
4653
Chris Lattner7ab824e2008-08-10 02:05:13 +00004654 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004655 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004656 diag::err_shufflevector_argument_too_large)
4657 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004658 }
4659
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004660 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004661
Chris Lattner7ab824e2008-08-10 02:05:13 +00004662 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004663 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004664 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004665 }
4666
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004667 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4668 TheCall->getCallee()->getLocStart(),
4669 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004670}
Chris Lattner43be2e62007-12-19 23:59:04 +00004671
Hal Finkelc4d7c822013-09-18 03:29:45 +00004672/// SemaConvertVectorExpr - Handle __builtin_convertvector
4673ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4674 SourceLocation BuiltinLoc,
4675 SourceLocation RParenLoc) {
4676 ExprValueKind VK = VK_RValue;
4677 ExprObjectKind OK = OK_Ordinary;
4678 QualType DstTy = TInfo->getType();
4679 QualType SrcTy = E->getType();
4680
4681 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4682 return ExprError(Diag(BuiltinLoc,
4683 diag::err_convertvector_non_vector)
4684 << E->getSourceRange());
4685 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4686 return ExprError(Diag(BuiltinLoc,
4687 diag::err_convertvector_non_vector_type));
4688
4689 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4690 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4691 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4692 if (SrcElts != DstElts)
4693 return ExprError(Diag(BuiltinLoc,
4694 diag::err_convertvector_incompatible_vector)
4695 << E->getSourceRange());
4696 }
4697
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004698 return new (Context)
4699 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004700}
4701
Daniel Dunbarb7257262008-07-21 22:59:13 +00004702/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4703// This is declared to take (const void*, ...) and can take two
4704// optional constant int args.
4705bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004706 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004707
Chris Lattner3b054132008-11-19 05:08:23 +00004708 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004709 return Diag(TheCall->getLocEnd(),
4710 diag::err_typecheck_call_too_many_args_at_most)
4711 << 0 /*function call*/ << 3 << NumArgs
4712 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004713
4714 // Argument 0 is checked for us and the remaining arguments must be
4715 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004716 for (unsigned i = 1; i != NumArgs; ++i)
4717 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004718 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004719
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004720 return false;
4721}
4722
Hal Finkelf0417332014-07-17 14:25:55 +00004723/// SemaBuiltinAssume - Handle __assume (MS Extension).
4724// __assume does not evaluate its arguments, and should warn if its argument
4725// has side effects.
4726bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4727 Expr *Arg = TheCall->getArg(0);
4728 if (Arg->isInstantiationDependent()) return false;
4729
4730 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004731 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004732 << Arg->getSourceRange()
4733 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4734
4735 return false;
4736}
4737
David Majnemer86b1bfa2016-10-31 18:07:57 +00004738/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004739/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4740/// than 8.
4741bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4742 // The alignment must be a constant integer.
4743 Expr *Arg = TheCall->getArg(1);
4744
4745 // We can't check the value of a dependent argument.
4746 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004747 if (const auto *UE =
4748 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4749 if (UE->getKind() == UETT_AlignOf)
4750 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4751 << Arg->getSourceRange();
4752
David Majnemer51169932016-10-31 05:37:48 +00004753 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4754
4755 if (!Result.isPowerOf2())
4756 return Diag(TheCall->getLocStart(),
4757 diag::err_alignment_not_power_of_two)
4758 << Arg->getSourceRange();
4759
4760 if (Result < Context.getCharWidth())
4761 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4762 << (unsigned)Context.getCharWidth()
4763 << Arg->getSourceRange();
4764
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004765 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004766 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004767 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004768 << Arg->getSourceRange();
4769 }
4770
4771 return false;
4772}
4773
4774/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004775/// as (const void*, size_t, ...) and can take one optional constant int arg.
4776bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4777 unsigned NumArgs = TheCall->getNumArgs();
4778
4779 if (NumArgs > 3)
4780 return Diag(TheCall->getLocEnd(),
4781 diag::err_typecheck_call_too_many_args_at_most)
4782 << 0 /*function call*/ << 3 << NumArgs
4783 << TheCall->getSourceRange();
4784
4785 // The alignment must be a constant integer.
4786 Expr *Arg = TheCall->getArg(1);
4787
4788 // We can't check the value of a dependent argument.
4789 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4790 llvm::APSInt Result;
4791 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4792 return true;
4793
4794 if (!Result.isPowerOf2())
4795 return Diag(TheCall->getLocStart(),
4796 diag::err_alignment_not_power_of_two)
4797 << Arg->getSourceRange();
4798 }
4799
4800 if (NumArgs > 2) {
4801 ExprResult Arg(TheCall->getArg(2));
4802 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4803 Context.getSizeType(), false);
4804 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4805 if (Arg.isInvalid()) return true;
4806 TheCall->setArg(2, Arg.get());
4807 }
Hal Finkelf0417332014-07-17 14:25:55 +00004808
4809 return false;
4810}
4811
Mehdi Amini06d367c2016-10-24 20:39:34 +00004812bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4813 unsigned BuiltinID =
4814 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4815 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4816
4817 unsigned NumArgs = TheCall->getNumArgs();
4818 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4819 if (NumArgs < NumRequiredArgs) {
4820 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4821 << 0 /* function call */ << NumRequiredArgs << NumArgs
4822 << TheCall->getSourceRange();
4823 }
4824 if (NumArgs >= NumRequiredArgs + 0x100) {
4825 return Diag(TheCall->getLocEnd(),
4826 diag::err_typecheck_call_too_many_args_at_most)
4827 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4828 << TheCall->getSourceRange();
4829 }
4830 unsigned i = 0;
4831
4832 // For formatting call, check buffer arg.
4833 if (!IsSizeCall) {
4834 ExprResult Arg(TheCall->getArg(i));
4835 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4836 Context, Context.VoidPtrTy, false);
4837 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4838 if (Arg.isInvalid())
4839 return true;
4840 TheCall->setArg(i, Arg.get());
4841 i++;
4842 }
4843
4844 // Check string literal arg.
4845 unsigned FormatIdx = i;
4846 {
4847 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4848 if (Arg.isInvalid())
4849 return true;
4850 TheCall->setArg(i, Arg.get());
4851 i++;
4852 }
4853
4854 // Make sure variadic args are scalar.
4855 unsigned FirstDataArg = i;
4856 while (i < NumArgs) {
4857 ExprResult Arg = DefaultVariadicArgumentPromotion(
4858 TheCall->getArg(i), VariadicFunction, nullptr);
4859 if (Arg.isInvalid())
4860 return true;
4861 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4862 if (ArgSize.getQuantity() >= 0x100) {
4863 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4864 << i << (int)ArgSize.getQuantity() << 0xff
4865 << TheCall->getSourceRange();
4866 }
4867 TheCall->setArg(i, Arg.get());
4868 i++;
4869 }
4870
4871 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4872 // call to avoid duplicate diagnostics.
4873 if (!IsSizeCall) {
4874 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4875 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4876 bool Success = CheckFormatArguments(
4877 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4878 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4879 CheckedVarArgs);
4880 if (!Success)
4881 return true;
4882 }
4883
4884 if (IsSizeCall) {
4885 TheCall->setType(Context.getSizeType());
4886 } else {
4887 TheCall->setType(Context.VoidPtrTy);
4888 }
4889 return false;
4890}
4891
Eric Christopher8d0c6212010-04-17 02:26:23 +00004892/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4893/// TheCall is a constant expression.
4894bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4895 llvm::APSInt &Result) {
4896 Expr *Arg = TheCall->getArg(ArgNum);
4897 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4898 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4899
4900 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4901
4902 if (!Arg->isIntegerConstantExpr(Result, Context))
4903 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004904 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004905
Chris Lattnerd545ad12009-09-23 06:06:36 +00004906 return false;
4907}
4908
Richard Sandiford28940af2014-04-16 08:47:51 +00004909/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4910/// TheCall is a constant expression in the range [Low, High].
4911bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4912 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004913 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004914
4915 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004916 Expr *Arg = TheCall->getArg(ArgNum);
4917 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004918 return false;
4919
Eric Christopher8d0c6212010-04-17 02:26:23 +00004920 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004921 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004922 return true;
4923
Richard Sandiford28940af2014-04-16 08:47:51 +00004924 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004925 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004926 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004927
4928 return false;
4929}
4930
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004931/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4932/// TheCall is a constant expression is a multiple of Num..
4933bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4934 unsigned Num) {
4935 llvm::APSInt Result;
4936
4937 // We can't check the value of a dependent argument.
4938 Expr *Arg = TheCall->getArg(ArgNum);
4939 if (Arg->isTypeDependent() || Arg->isValueDependent())
4940 return false;
4941
4942 // Check constant-ness first.
4943 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4944 return true;
4945
4946 if (Result.getSExtValue() % Num != 0)
4947 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4948 << Num << Arg->getSourceRange();
4949
4950 return false;
4951}
4952
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004953/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4954/// TheCall is an ARM/AArch64 special register string literal.
4955bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4956 int ArgNum, unsigned ExpectedFieldNum,
4957 bool AllowName) {
4958 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4959 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4960 BuiltinID == ARM::BI__builtin_arm_rsr ||
4961 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4962 BuiltinID == ARM::BI__builtin_arm_wsr ||
4963 BuiltinID == ARM::BI__builtin_arm_wsrp;
4964 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4965 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4966 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4967 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4968 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4969 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4970 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4971
4972 // We can't check the value of a dependent argument.
4973 Expr *Arg = TheCall->getArg(ArgNum);
4974 if (Arg->isTypeDependent() || Arg->isValueDependent())
4975 return false;
4976
4977 // Check if the argument is a string literal.
4978 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4979 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4980 << Arg->getSourceRange();
4981
4982 // Check the type of special register given.
4983 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4984 SmallVector<StringRef, 6> Fields;
4985 Reg.split(Fields, ":");
4986
4987 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4988 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4989 << Arg->getSourceRange();
4990
4991 // If the string is the name of a register then we cannot check that it is
4992 // valid here but if the string is of one the forms described in ACLE then we
4993 // can check that the supplied fields are integers and within the valid
4994 // ranges.
4995 if (Fields.size() > 1) {
4996 bool FiveFields = Fields.size() == 5;
4997
4998 bool ValidString = true;
4999 if (IsARMBuiltin) {
5000 ValidString &= Fields[0].startswith_lower("cp") ||
5001 Fields[0].startswith_lower("p");
5002 if (ValidString)
5003 Fields[0] =
5004 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5005
5006 ValidString &= Fields[2].startswith_lower("c");
5007 if (ValidString)
5008 Fields[2] = Fields[2].drop_front(1);
5009
5010 if (FiveFields) {
5011 ValidString &= Fields[3].startswith_lower("c");
5012 if (ValidString)
5013 Fields[3] = Fields[3].drop_front(1);
5014 }
5015 }
5016
5017 SmallVector<int, 5> Ranges;
5018 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00005019 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005020 else
5021 Ranges.append({15, 7, 15});
5022
5023 for (unsigned i=0; i<Fields.size(); ++i) {
5024 int IntField;
5025 ValidString &= !Fields[i].getAsInteger(10, IntField);
5026 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5027 }
5028
5029 if (!ValidString)
5030 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5031 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005032 } else if (IsAArch64Builtin && Fields.size() == 1) {
5033 // If the register name is one of those that appear in the condition below
5034 // and the special register builtin being used is one of the write builtins,
5035 // then we require that the argument provided for writing to the register
5036 // is an integer constant expression. This is because it will be lowered to
5037 // an MSR (immediate) instruction, so we need to know the immediate at
5038 // compile time.
5039 if (TheCall->getNumArgs() != 2)
5040 return false;
5041
5042 std::string RegLower = Reg.lower();
5043 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5044 RegLower != "pan" && RegLower != "uao")
5045 return false;
5046
5047 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5048 }
5049
5050 return false;
5051}
5052
Eli Friedmanc97d0142009-05-03 06:04:26 +00005053/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005054/// This checks that the target supports __builtin_longjmp and
5055/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005056bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005057 if (!Context.getTargetInfo().hasSjLjLowering())
5058 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5059 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5060
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005061 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00005062 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00005063
Eric Christopher8d0c6212010-04-17 02:26:23 +00005064 // TODO: This is less than ideal. Overload this to take a value.
5065 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5066 return true;
5067
5068 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005069 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5070 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5071
5072 return false;
5073}
5074
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005075/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5076/// This checks that the target supports __builtin_setjmp.
5077bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5078 if (!Context.getTargetInfo().hasSjLjLowering())
5079 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5080 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5081 return false;
5082}
5083
Richard Smithd7293d72013-08-05 18:49:43 +00005084namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005085
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005086class UncoveredArgHandler {
5087 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005088
5089 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005090 SmallVector<const Expr *, 4> DiagnosticExprs;
5091
5092public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005093 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005094
5095 bool hasUncoveredArg() const {
5096 return (FirstUncoveredArg >= 0);
5097 }
5098
5099 unsigned getUncoveredArg() const {
5100 assert(hasUncoveredArg() && "no uncovered argument");
5101 return FirstUncoveredArg;
5102 }
5103
5104 void setAllCovered() {
5105 // A string has been found with all arguments covered, so clear out
5106 // the diagnostics.
5107 DiagnosticExprs.clear();
5108 FirstUncoveredArg = AllCovered;
5109 }
5110
5111 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5112 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5113
5114 // Don't update if a previous string covers all arguments.
5115 if (FirstUncoveredArg == AllCovered)
5116 return;
5117
5118 // UncoveredArgHandler tracks the highest uncovered argument index
5119 // and with it all the strings that match this index.
5120 if (NewFirstUncoveredArg == FirstUncoveredArg)
5121 DiagnosticExprs.push_back(StrExpr);
5122 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5123 DiagnosticExprs.clear();
5124 DiagnosticExprs.push_back(StrExpr);
5125 FirstUncoveredArg = NewFirstUncoveredArg;
5126 }
5127 }
5128
5129 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5130};
5131
Richard Smithd7293d72013-08-05 18:49:43 +00005132enum StringLiteralCheckType {
5133 SLCT_NotALiteral,
5134 SLCT_UncheckedLiteral,
5135 SLCT_CheckedLiteral
5136};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005137
5138} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005139
Stephen Hines648c3692016-09-16 01:07:04 +00005140static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5141 BinaryOperatorKind BinOpKind,
5142 bool AddendIsRight) {
5143 unsigned BitWidth = Offset.getBitWidth();
5144 unsigned AddendBitWidth = Addend.getBitWidth();
5145 // There might be negative interim results.
5146 if (Addend.isUnsigned()) {
5147 Addend = Addend.zext(++AddendBitWidth);
5148 Addend.setIsSigned(true);
5149 }
5150 // Adjust the bit width of the APSInts.
5151 if (AddendBitWidth > BitWidth) {
5152 Offset = Offset.sext(AddendBitWidth);
5153 BitWidth = AddendBitWidth;
5154 } else if (BitWidth > AddendBitWidth) {
5155 Addend = Addend.sext(BitWidth);
5156 }
5157
5158 bool Ov = false;
5159 llvm::APSInt ResOffset = Offset;
5160 if (BinOpKind == BO_Add)
5161 ResOffset = Offset.sadd_ov(Addend, Ov);
5162 else {
5163 assert(AddendIsRight && BinOpKind == BO_Sub &&
5164 "operator must be add or sub with addend on the right");
5165 ResOffset = Offset.ssub_ov(Addend, Ov);
5166 }
5167
5168 // We add an offset to a pointer here so we should support an offset as big as
5169 // possible.
5170 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005171 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5172 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005173 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005174 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5175 return;
5176 }
5177
5178 Offset = ResOffset;
5179}
5180
5181namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005182
Stephen Hines648c3692016-09-16 01:07:04 +00005183// This is a wrapper class around StringLiteral to support offsetted string
5184// literals as format strings. It takes the offset into account when returning
5185// the string and its length or the source locations to display notes correctly.
5186class FormatStringLiteral {
5187 const StringLiteral *FExpr;
5188 int64_t Offset;
5189
5190 public:
5191 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5192 : FExpr(fexpr), Offset(Offset) {}
5193
5194 StringRef getString() const {
5195 return FExpr->getString().drop_front(Offset);
5196 }
5197
5198 unsigned getByteLength() const {
5199 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5200 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005201
Stephen Hines648c3692016-09-16 01:07:04 +00005202 unsigned getLength() const { return FExpr->getLength() - Offset; }
5203 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5204
5205 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5206
5207 QualType getType() const { return FExpr->getType(); }
5208
5209 bool isAscii() const { return FExpr->isAscii(); }
5210 bool isWide() const { return FExpr->isWide(); }
5211 bool isUTF8() const { return FExpr->isUTF8(); }
5212 bool isUTF16() const { return FExpr->isUTF16(); }
5213 bool isUTF32() const { return FExpr->isUTF32(); }
5214 bool isPascal() const { return FExpr->isPascal(); }
5215
5216 SourceLocation getLocationOfByte(
5217 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5218 const TargetInfo &Target, unsigned *StartToken = nullptr,
5219 unsigned *StartTokenByteOffset = nullptr) const {
5220 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5221 StartToken, StartTokenByteOffset);
5222 }
5223
5224 SourceLocation getLocStart() const LLVM_READONLY {
5225 return FExpr->getLocStart().getLocWithOffset(Offset);
5226 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005227
Stephen Hines648c3692016-09-16 01:07:04 +00005228 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5229};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005230
5231} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005232
5233static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005234 const Expr *OrigFormatExpr,
5235 ArrayRef<const Expr *> Args,
5236 bool HasVAListArg, unsigned format_idx,
5237 unsigned firstDataArg,
5238 Sema::FormatStringType Type,
5239 bool inFunctionCall,
5240 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005241 llvm::SmallBitVector &CheckedVarArgs,
5242 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005243
Richard Smith55ce3522012-06-25 20:30:08 +00005244// Determine if an expression is a string literal or constant string.
5245// If this function returns false on the arguments to a function expecting a
5246// format string, we will usually need to emit a warning.
5247// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005248static StringLiteralCheckType
5249checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5250 bool HasVAListArg, unsigned format_idx,
5251 unsigned firstDataArg, Sema::FormatStringType Type,
5252 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005253 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005254 UncoveredArgHandler &UncoveredArg,
5255 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005256 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005257 assert(Offset.isSigned() && "invalid offset");
5258
Douglas Gregorc25f7662009-05-19 22:10:17 +00005259 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005260 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005261
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005262 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005263
Richard Smithd7293d72013-08-05 18:49:43 +00005264 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005265 // Technically -Wformat-nonliteral does not warn about this case.
5266 // The behavior of printf and friends in this case is implementation
5267 // dependent. Ideally if the format string cannot be null then
5268 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005269 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005270
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005271 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005272 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005273 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005274 // The expression is a literal if both sub-expressions were, and it was
5275 // completely checked only if both sub-expressions were checked.
5276 const AbstractConditionalOperator *C =
5277 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005278
5279 // Determine whether it is necessary to check both sub-expressions, for
5280 // example, because the condition expression is a constant that can be
5281 // evaluated at compile time.
5282 bool CheckLeft = true, CheckRight = true;
5283
5284 bool Cond;
5285 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5286 if (Cond)
5287 CheckRight = false;
5288 else
5289 CheckLeft = false;
5290 }
5291
Stephen Hines648c3692016-09-16 01:07:04 +00005292 // We need to maintain the offsets for the right and the left hand side
5293 // separately to check if every possible indexed expression is a valid
5294 // string literal. They might have different offsets for different string
5295 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005296 StringLiteralCheckType Left;
5297 if (!CheckLeft)
5298 Left = SLCT_UncheckedLiteral;
5299 else {
5300 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5301 HasVAListArg, format_idx, firstDataArg,
5302 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005303 CheckedVarArgs, UncoveredArg, Offset);
5304 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005305 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005306 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005307 }
5308
Richard Smith55ce3522012-06-25 20:30:08 +00005309 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005310 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005311 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005312 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005313 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005314
5315 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005316 }
5317
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005318 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005319 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5320 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005321
John McCallc07a0c72011-02-17 10:25:35 +00005322 case Stmt::OpaqueValueExprClass:
5323 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5324 E = src;
5325 goto tryAgain;
5326 }
Richard Smith55ce3522012-06-25 20:30:08 +00005327 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005328
Ted Kremeneka8890832011-02-24 23:03:04 +00005329 case Stmt::PredefinedExprClass:
5330 // While __func__, etc., are technically not string literals, they
5331 // cannot contain format specifiers and thus are not a security
5332 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005333 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005334
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005335 case Stmt::DeclRefExprClass: {
5336 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005337
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005338 // As an exception, do not flag errors for variables binding to
5339 // const string literals.
5340 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5341 bool isConstant = false;
5342 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005343
Richard Smithd7293d72013-08-05 18:49:43 +00005344 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5345 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005346 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005347 isConstant = T.isConstant(S.Context) &&
5348 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005349 } else if (T->isObjCObjectPointerType()) {
5350 // In ObjC, there is usually no "const ObjectPointer" type,
5351 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005352 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005353 }
Mike Stump11289f42009-09-09 15:08:12 +00005354
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005355 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005356 if (const Expr *Init = VD->getAnyInitializer()) {
5357 // Look through initializers like const char c[] = { "foo" }
5358 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5359 if (InitList->isStringLiteralInit())
5360 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5361 }
Richard Smithd7293d72013-08-05 18:49:43 +00005362 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005363 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005364 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005365 /*InFunctionCall*/ false, CheckedVarArgs,
5366 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005367 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005368 }
Mike Stump11289f42009-09-09 15:08:12 +00005369
Anders Carlssonb012ca92009-06-28 19:55:58 +00005370 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5371 // special check to see if the format string is a function parameter
5372 // of the function calling the printf function. If the function
5373 // has an attribute indicating it is a printf-like function, then we
5374 // should suppress warnings concerning non-literals being used in a call
5375 // to a vprintf function. For example:
5376 //
5377 // void
5378 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5379 // va_list ap;
5380 // va_start(ap, fmt);
5381 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5382 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005383 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005384 if (HasVAListArg) {
5385 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5386 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5387 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005388 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005389 // adjust for implicit parameter
5390 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5391 if (MD->isInstance())
5392 ++PVIndex;
5393 // We also check if the formats are compatible.
5394 // We can't pass a 'scanf' string to a 'printf' function.
5395 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005396 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005397 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005398 }
5399 }
5400 }
5401 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005402 }
Mike Stump11289f42009-09-09 15:08:12 +00005403
Richard Smith55ce3522012-06-25 20:30:08 +00005404 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005405 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005406
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005407 case Stmt::CallExprClass:
5408 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005409 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005410 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5411 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005412 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005413 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005414 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005415 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005416 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005417 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5418 unsigned BuiltinID = FD->getBuiltinID();
5419 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5420 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5421 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005422 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005423 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005424 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005425 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005426 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005427 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005428 }
5429 }
Mike Stump11289f42009-09-09 15:08:12 +00005430
Richard Smith55ce3522012-06-25 20:30:08 +00005431 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005432 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005433 case Stmt::ObjCMessageExprClass: {
5434 const auto *ME = cast<ObjCMessageExpr>(E);
5435 if (const auto *ND = ME->getMethodDecl()) {
5436 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005437 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005438 return checkFormatStringExpr(
5439 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5440 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5441 }
5442 }
5443
5444 return SLCT_NotALiteral;
5445 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005446 case Stmt::ObjCStringLiteralClass:
5447 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005448 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005449
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005450 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005451 StrE = ObjCFExpr->getString();
5452 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005453 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005454
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005455 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005456 if (Offset.isNegative() || Offset > StrE->getLength()) {
5457 // TODO: It would be better to have an explicit warning for out of
5458 // bounds literals.
5459 return SLCT_NotALiteral;
5460 }
5461 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5462 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005463 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005464 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005465 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005466 }
Mike Stump11289f42009-09-09 15:08:12 +00005467
Richard Smith55ce3522012-06-25 20:30:08 +00005468 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005469 }
Stephen Hines648c3692016-09-16 01:07:04 +00005470 case Stmt::BinaryOperatorClass: {
5471 llvm::APSInt LResult;
5472 llvm::APSInt RResult;
5473
5474 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5475
5476 // A string literal + an int offset is still a string literal.
5477 if (BinOp->isAdditiveOp()) {
5478 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5479 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5480
5481 if (LIsInt != RIsInt) {
5482 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5483
5484 if (LIsInt) {
5485 if (BinOpKind == BO_Add) {
5486 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5487 E = BinOp->getRHS();
5488 goto tryAgain;
5489 }
5490 } else {
5491 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5492 E = BinOp->getLHS();
5493 goto tryAgain;
5494 }
5495 }
Stephen Hines648c3692016-09-16 01:07:04 +00005496 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005497
5498 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005499 }
5500 case Stmt::UnaryOperatorClass: {
5501 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5502 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005503 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005504 llvm::APSInt IndexResult;
5505 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5506 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5507 E = ASE->getBase();
5508 goto tryAgain;
5509 }
5510 }
5511
5512 return SLCT_NotALiteral;
5513 }
Mike Stump11289f42009-09-09 15:08:12 +00005514
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005515 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005516 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005517 }
5518}
5519
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005520Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005521 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005522 .Case("scanf", FST_Scanf)
5523 .Cases("printf", "printf0", FST_Printf)
5524 .Cases("NSString", "CFString", FST_NSString)
5525 .Case("strftime", FST_Strftime)
5526 .Case("strfmon", FST_Strfmon)
5527 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5528 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5529 .Case("os_trace", FST_OSLog)
5530 .Case("os_log", FST_OSLog)
5531 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005532}
5533
Jordan Rose3e0ec582012-07-19 18:10:23 +00005534/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005535/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005536/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005537bool Sema::CheckFormatArguments(const FormatAttr *Format,
5538 ArrayRef<const Expr *> Args,
5539 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005540 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005541 SourceLocation Loc, SourceRange Range,
5542 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005543 FormatStringInfo FSI;
5544 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005545 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005546 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005547 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005548 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005549}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005550
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005551bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005552 bool HasVAListArg, unsigned format_idx,
5553 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005554 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005555 SourceLocation Loc, SourceRange Range,
5556 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005557 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005558 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005559 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005560 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005561 }
Mike Stump11289f42009-09-09 15:08:12 +00005562
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005563 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005564
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005565 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005566 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005567 // Dynamically generated format strings are difficult to
5568 // automatically vet at compile time. Requiring that format strings
5569 // are string literals: (1) permits the checking of format strings by
5570 // the compiler and thereby (2) can practically remove the source of
5571 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005572
Mike Stump11289f42009-09-09 15:08:12 +00005573 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005574 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005575 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005576 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005577 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005578 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005579 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5580 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005581 /*IsFunctionCall*/ true, CheckedVarArgs,
5582 UncoveredArg,
5583 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005584
5585 // Generate a diagnostic where an uncovered argument is detected.
5586 if (UncoveredArg.hasUncoveredArg()) {
5587 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5588 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5589 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5590 }
5591
Richard Smith55ce3522012-06-25 20:30:08 +00005592 if (CT != SLCT_NotALiteral)
5593 // Literal format string found, check done!
5594 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005595
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005596 // Strftime is particular as it always uses a single 'time' argument,
5597 // so it is safe to pass a non-literal string.
5598 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005599 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005600
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005601 // Do not emit diag when the string param is a macro expansion and the
5602 // format is either NSString or CFString. This is a hack to prevent
5603 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5604 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005605 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5606 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005607 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005608
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005609 // If there are no arguments specified, warn with -Wformat-security, otherwise
5610 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005611 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005612 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5613 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005614 switch (Type) {
5615 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005616 break;
5617 case FST_Kprintf:
5618 case FST_FreeBSDKPrintf:
5619 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005620 Diag(FormatLoc, diag::note_format_security_fixit)
5621 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005622 break;
5623 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005624 Diag(FormatLoc, diag::note_format_security_fixit)
5625 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005626 break;
5627 }
5628 } else {
5629 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005630 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005631 }
Richard Smith55ce3522012-06-25 20:30:08 +00005632 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005633}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005634
Ted Kremenekab278de2010-01-28 23:39:18 +00005635namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005636
Ted Kremenek02087932010-07-16 02:11:22 +00005637class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5638protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005639 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005640 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005641 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005642 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005643 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005644 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005645 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005646 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005647 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005648 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005649 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005650 bool usesPositionalArgs = false;
5651 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005652 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005653 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005654 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005655 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005656
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005657public:
Stephen Hines648c3692016-09-16 01:07:04 +00005658 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005659 const Expr *origFormatExpr,
5660 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005661 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005662 ArrayRef<const Expr *> Args, unsigned formatIdx,
5663 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005664 llvm::SmallBitVector &CheckedVarArgs,
5665 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005666 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5667 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5668 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005669 inFunctionCall(inFunctionCall), CallType(callType),
5670 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005671 CoveredArgs.resize(numDataArgs);
5672 CoveredArgs.reset();
5673 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005674
Ted Kremenek019d2242010-01-29 01:50:07 +00005675 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005676
Ted Kremenek02087932010-07-16 02:11:22 +00005677 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005678 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005679
Jordan Rose92303592012-09-08 04:00:03 +00005680 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005681 const analyze_format_string::FormatSpecifier &FS,
5682 const analyze_format_string::ConversionSpecifier &CS,
5683 const char *startSpecifier, unsigned specifierLen,
5684 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005685
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005686 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005687 const analyze_format_string::FormatSpecifier &FS,
5688 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005689
5690 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005691 const analyze_format_string::ConversionSpecifier &CS,
5692 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005693
Craig Toppere14c0f82014-03-12 04:55:44 +00005694 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005695
Craig Toppere14c0f82014-03-12 04:55:44 +00005696 void HandleInvalidPosition(const char *startSpecifier,
5697 unsigned specifierLen,
5698 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005699
Craig Toppere14c0f82014-03-12 04:55:44 +00005700 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005701
Craig Toppere14c0f82014-03-12 04:55:44 +00005702 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005703
Richard Trieu03cf7b72011-10-28 00:41:25 +00005704 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005705 static void
5706 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5707 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5708 bool IsStringLocation, Range StringRange,
5709 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005710
Ted Kremenek02087932010-07-16 02:11:22 +00005711protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005712 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5713 const char *startSpec,
5714 unsigned specifierLen,
5715 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005716
5717 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5718 const char *startSpec,
5719 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005720
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005721 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005722 CharSourceRange getSpecifierRange(const char *startSpecifier,
5723 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005724 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005725
Ted Kremenek5739de72010-01-29 01:06:55 +00005726 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005727
5728 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5729 const analyze_format_string::ConversionSpecifier &CS,
5730 const char *startSpecifier, unsigned specifierLen,
5731 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005732
5733 template <typename Range>
5734 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5735 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005736 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005737};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005738
5739} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005740
Ted Kremenek02087932010-07-16 02:11:22 +00005741SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005742 return OrigFormatExpr->getSourceRange();
5743}
5744
Ted Kremenek02087932010-07-16 02:11:22 +00005745CharSourceRange CheckFormatHandler::
5746getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005747 SourceLocation Start = getLocationOfByte(startSpecifier);
5748 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5749
5750 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005751 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005752
5753 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005754}
5755
Ted Kremenek02087932010-07-16 02:11:22 +00005756SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005757 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5758 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005759}
5760
Ted Kremenek02087932010-07-16 02:11:22 +00005761void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5762 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005763 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5764 getLocationOfByte(startSpecifier),
5765 /*IsStringLocation*/true,
5766 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005767}
5768
Jordan Rose92303592012-09-08 04:00:03 +00005769void CheckFormatHandler::HandleInvalidLengthModifier(
5770 const analyze_format_string::FormatSpecifier &FS,
5771 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005772 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005773 using namespace analyze_format_string;
5774
5775 const LengthModifier &LM = FS.getLengthModifier();
5776 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5777
5778 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005779 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005780 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005781 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005782 getLocationOfByte(LM.getStart()),
5783 /*IsStringLocation*/true,
5784 getSpecifierRange(startSpecifier, specifierLen));
5785
5786 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5787 << FixedLM->toString()
5788 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5789
5790 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005791 FixItHint Hint;
5792 if (DiagID == diag::warn_format_nonsensical_length)
5793 Hint = FixItHint::CreateRemoval(LMRange);
5794
5795 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005796 getLocationOfByte(LM.getStart()),
5797 /*IsStringLocation*/true,
5798 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005799 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005800 }
5801}
5802
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005803void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005804 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005805 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005806 using namespace analyze_format_string;
5807
5808 const LengthModifier &LM = FS.getLengthModifier();
5809 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5810
5811 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005812 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005813 if (FixedLM) {
5814 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5815 << LM.toString() << 0,
5816 getLocationOfByte(LM.getStart()),
5817 /*IsStringLocation*/true,
5818 getSpecifierRange(startSpecifier, specifierLen));
5819
5820 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5821 << FixedLM->toString()
5822 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5823
5824 } else {
5825 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5826 << LM.toString() << 0,
5827 getLocationOfByte(LM.getStart()),
5828 /*IsStringLocation*/true,
5829 getSpecifierRange(startSpecifier, specifierLen));
5830 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005831}
5832
5833void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5834 const analyze_format_string::ConversionSpecifier &CS,
5835 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005836 using namespace analyze_format_string;
5837
5838 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005839 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005840 if (FixedCS) {
5841 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5842 << CS.toString() << /*conversion specifier*/1,
5843 getLocationOfByte(CS.getStart()),
5844 /*IsStringLocation*/true,
5845 getSpecifierRange(startSpecifier, specifierLen));
5846
5847 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5848 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5849 << FixedCS->toString()
5850 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5851 } else {
5852 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5853 << CS.toString() << /*conversion specifier*/1,
5854 getLocationOfByte(CS.getStart()),
5855 /*IsStringLocation*/true,
5856 getSpecifierRange(startSpecifier, specifierLen));
5857 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005858}
5859
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005860void CheckFormatHandler::HandlePosition(const char *startPos,
5861 unsigned posLen) {
5862 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5863 getLocationOfByte(startPos),
5864 /*IsStringLocation*/true,
5865 getSpecifierRange(startPos, posLen));
5866}
5867
Ted Kremenekd1668192010-02-27 01:41:03 +00005868void
Ted Kremenek02087932010-07-16 02:11:22 +00005869CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5870 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005871 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5872 << (unsigned) p,
5873 getLocationOfByte(startPos), /*IsStringLocation*/true,
5874 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005875}
5876
Ted Kremenek02087932010-07-16 02:11:22 +00005877void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005878 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005879 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5880 getLocationOfByte(startPos),
5881 /*IsStringLocation*/true,
5882 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005883}
5884
Ted Kremenek02087932010-07-16 02:11:22 +00005885void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005886 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005887 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005888 EmitFormatDiagnostic(
5889 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5890 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5891 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005892 }
Ted Kremenek02087932010-07-16 02:11:22 +00005893}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005894
Jordan Rose58bbe422012-07-19 18:10:08 +00005895// Note that this may return NULL if there was an error parsing or building
5896// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005897const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005898 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005899}
5900
5901void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005902 // Does the number of data arguments exceed the number of
5903 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005904 if (!HasVAListArg) {
5905 // Find any arguments that weren't covered.
5906 CoveredArgs.flip();
5907 signed notCoveredArg = CoveredArgs.find_first();
5908 if (notCoveredArg >= 0) {
5909 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005910 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5911 } else {
5912 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005913 }
5914 }
5915}
5916
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005917void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5918 const Expr *ArgExpr) {
5919 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5920 "Invalid state");
5921
5922 if (!ArgExpr)
5923 return;
5924
5925 SourceLocation Loc = ArgExpr->getLocStart();
5926
5927 if (S.getSourceManager().isInSystemMacro(Loc))
5928 return;
5929
5930 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5931 for (auto E : DiagnosticExprs)
5932 PDiag << E->getSourceRange();
5933
5934 CheckFormatHandler::EmitFormatDiagnostic(
5935 S, IsFunctionCall, DiagnosticExprs[0],
5936 PDiag, Loc, /*IsStringLocation*/false,
5937 DiagnosticExprs[0]->getSourceRange());
5938}
5939
Ted Kremenekce815422010-07-19 21:25:57 +00005940bool
5941CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5942 SourceLocation Loc,
5943 const char *startSpec,
5944 unsigned specifierLen,
5945 const char *csStart,
5946 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005947 bool keepGoing = true;
5948 if (argIndex < NumDataArgs) {
5949 // Consider the argument coverered, even though the specifier doesn't
5950 // make sense.
5951 CoveredArgs.set(argIndex);
5952 }
5953 else {
5954 // If argIndex exceeds the number of data arguments we
5955 // don't issue a warning because that is just a cascade of warnings (and
5956 // they may have intended '%%' anyway). We don't want to continue processing
5957 // the format string after this point, however, as we will like just get
5958 // gibberish when trying to match arguments.
5959 keepGoing = false;
5960 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005961
5962 StringRef Specifier(csStart, csLen);
5963
5964 // If the specifier in non-printable, it could be the first byte of a UTF-8
5965 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5966 // hex value.
5967 std::string CodePointStr;
5968 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005969 llvm::UTF32 CodePoint;
5970 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5971 const llvm::UTF8 *E =
5972 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5973 llvm::ConversionResult Result =
5974 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005975
Justin Lebar90910552016-09-30 00:38:45 +00005976 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005977 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005978 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005979 }
5980
5981 llvm::raw_string_ostream OS(CodePointStr);
5982 if (CodePoint < 256)
5983 OS << "\\x" << llvm::format("%02x", CodePoint);
5984 else if (CodePoint <= 0xFFFF)
5985 OS << "\\u" << llvm::format("%04x", CodePoint);
5986 else
5987 OS << "\\U" << llvm::format("%08x", CodePoint);
5988 OS.flush();
5989 Specifier = CodePointStr;
5990 }
5991
5992 EmitFormatDiagnostic(
5993 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5994 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5995
Ted Kremenekce815422010-07-19 21:25:57 +00005996 return keepGoing;
5997}
5998
Richard Trieu03cf7b72011-10-28 00:41:25 +00005999void
6000CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6001 const char *startSpec,
6002 unsigned specifierLen) {
6003 EmitFormatDiagnostic(
6004 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6005 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6006}
6007
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006008bool
6009CheckFormatHandler::CheckNumArgs(
6010 const analyze_format_string::FormatSpecifier &FS,
6011 const analyze_format_string::ConversionSpecifier &CS,
6012 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6013
6014 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006015 PartialDiagnostic PDiag = FS.usesPositionalArg()
6016 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6017 << (argIndex+1) << NumDataArgs)
6018 : S.PDiag(diag::warn_printf_insufficient_data_args);
6019 EmitFormatDiagnostic(
6020 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6021 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006022
6023 // Since more arguments than conversion tokens are given, by extension
6024 // all arguments are covered, so mark this as so.
6025 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006026 return false;
6027 }
6028 return true;
6029}
6030
Richard Trieu03cf7b72011-10-28 00:41:25 +00006031template<typename Range>
6032void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6033 SourceLocation Loc,
6034 bool IsStringLocation,
6035 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00006036 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006037 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00006038 Loc, IsStringLocation, StringRange, FixIt);
6039}
6040
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006041/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00006042/// so that the function call and string are in diagnostic messages.
6043///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006044/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00006045/// call and only one diagnostic message will be produced. Otherwise, an
6046/// extra note will be emitted pointing to location of the format string.
6047///
6048/// \param ArgumentExpr the expression that is passed as the format string
6049/// argument in the function call. Used for getting locations when two
6050/// diagnostics are emitted.
6051///
6052/// \param PDiag the callee should already have provided any strings for the
6053/// diagnostic message. This function only adds locations and fixits
6054/// to diagnostics.
6055///
6056/// \param Loc primary location for diagnostic. If two diagnostics are
6057/// required, one will be at Loc and a new SourceLocation will be created for
6058/// the other one.
6059///
6060/// \param IsStringLocation if true, Loc points to the format string should be
6061/// used for the note. Otherwise, Loc points to the argument list and will
6062/// be used with PDiag.
6063///
6064/// \param StringRange some or all of the string to highlight. This is
6065/// templated so it can accept either a CharSourceRange or a SourceRange.
6066///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006067/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00006068template <typename Range>
6069void CheckFormatHandler::EmitFormatDiagnostic(
6070 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6071 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6072 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00006073 if (InFunctionCall) {
6074 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6075 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006076 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006077 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006078 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6079 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006080
6081 const Sema::SemaDiagnosticBuilder &Note =
6082 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6083 diag::note_format_string_defined);
6084
6085 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006086 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006087 }
6088}
6089
Ted Kremenek02087932010-07-16 02:11:22 +00006090//===--- CHECK: Printf format string checking ------------------------------===//
6091
6092namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006093
Ted Kremenek02087932010-07-16 02:11:22 +00006094class CheckPrintfHandler : public CheckFormatHandler {
6095public:
Stephen Hines648c3692016-09-16 01:07:04 +00006096 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006097 const Expr *origFormatExpr,
6098 const Sema::FormatStringType type, unsigned firstDataArg,
6099 unsigned numDataArgs, bool isObjC, const char *beg,
6100 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006101 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006102 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006103 llvm::SmallBitVector &CheckedVarArgs,
6104 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006105 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6106 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6107 inFunctionCall, CallType, CheckedVarArgs,
6108 UncoveredArg) {}
6109
6110 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6111
6112 /// Returns true if '%@' specifiers are allowed in the format string.
6113 bool allowsObjCArg() const {
6114 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6115 FSType == Sema::FST_OSTrace;
6116 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006117
Ted Kremenek02087932010-07-16 02:11:22 +00006118 bool HandleInvalidPrintfConversionSpecifier(
6119 const analyze_printf::PrintfSpecifier &FS,
6120 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006121 unsigned specifierLen) override;
6122
Ted Kremenek02087932010-07-16 02:11:22 +00006123 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6124 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006125 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006126 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6127 const char *StartSpecifier,
6128 unsigned SpecifierLen,
6129 const Expr *E);
6130
Ted Kremenek02087932010-07-16 02:11:22 +00006131 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6132 const char *startSpecifier, unsigned specifierLen);
6133 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6134 const analyze_printf::OptionalAmount &Amt,
6135 unsigned type,
6136 const char *startSpecifier, unsigned specifierLen);
6137 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6138 const analyze_printf::OptionalFlag &flag,
6139 const char *startSpecifier, unsigned specifierLen);
6140 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6141 const analyze_printf::OptionalFlag &ignoredFlag,
6142 const analyze_printf::OptionalFlag &flag,
6143 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006144 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006145 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006146
6147 void HandleEmptyObjCModifierFlag(const char *startFlag,
6148 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006149
Ted Kremenek2b417712015-07-02 05:39:16 +00006150 void HandleInvalidObjCModifierFlag(const char *startFlag,
6151 unsigned flagLen) override;
6152
6153 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6154 const char *flagsEnd,
6155 const char *conversionPosition)
6156 override;
6157};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006158
6159} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006160
6161bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6162 const analyze_printf::PrintfSpecifier &FS,
6163 const char *startSpecifier,
6164 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006165 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006166 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006167
Ted Kremenekce815422010-07-19 21:25:57 +00006168 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6169 getLocationOfByte(CS.getStart()),
6170 startSpecifier, specifierLen,
6171 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006172}
6173
Ted Kremenek02087932010-07-16 02:11:22 +00006174bool CheckPrintfHandler::HandleAmount(
6175 const analyze_format_string::OptionalAmount &Amt,
6176 unsigned k, const char *startSpecifier,
6177 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006178 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006179 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006180 unsigned argIndex = Amt.getArgIndex();
6181 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006182 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6183 << k,
6184 getLocationOfByte(Amt.getStart()),
6185 /*IsStringLocation*/true,
6186 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006187 // Don't do any more checking. We will just emit
6188 // spurious errors.
6189 return false;
6190 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006191
Ted Kremenek5739de72010-01-29 01:06:55 +00006192 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006193 // Although not in conformance with C99, we also allow the argument to be
6194 // an 'unsigned int' as that is a reasonably safe case. GCC also
6195 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006196 CoveredArgs.set(argIndex);
6197 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006198 if (!Arg)
6199 return false;
6200
Ted Kremenek5739de72010-01-29 01:06:55 +00006201 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006202
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006203 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6204 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006205
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006206 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006207 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006208 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006209 << T << Arg->getSourceRange(),
6210 getLocationOfByte(Amt.getStart()),
6211 /*IsStringLocation*/true,
6212 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006213 // Don't do any more checking. We will just emit
6214 // spurious errors.
6215 return false;
6216 }
6217 }
6218 }
6219 return true;
6220}
Ted Kremenek5739de72010-01-29 01:06:55 +00006221
Tom Careb49ec692010-06-17 19:00:27 +00006222void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006223 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006224 const analyze_printf::OptionalAmount &Amt,
6225 unsigned type,
6226 const char *startSpecifier,
6227 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006228 const analyze_printf::PrintfConversionSpecifier &CS =
6229 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006230
Richard Trieu03cf7b72011-10-28 00:41:25 +00006231 FixItHint fixit =
6232 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6233 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6234 Amt.getConstantLength()))
6235 : FixItHint();
6236
6237 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6238 << type << CS.toString(),
6239 getLocationOfByte(Amt.getStart()),
6240 /*IsStringLocation*/true,
6241 getSpecifierRange(startSpecifier, specifierLen),
6242 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006243}
6244
Ted Kremenek02087932010-07-16 02:11:22 +00006245void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006246 const analyze_printf::OptionalFlag &flag,
6247 const char *startSpecifier,
6248 unsigned specifierLen) {
6249 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006250 const analyze_printf::PrintfConversionSpecifier &CS =
6251 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006252 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6253 << flag.toString() << CS.toString(),
6254 getLocationOfByte(flag.getPosition()),
6255 /*IsStringLocation*/true,
6256 getSpecifierRange(startSpecifier, specifierLen),
6257 FixItHint::CreateRemoval(
6258 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006259}
6260
6261void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006262 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006263 const analyze_printf::OptionalFlag &ignoredFlag,
6264 const analyze_printf::OptionalFlag &flag,
6265 const char *startSpecifier,
6266 unsigned specifierLen) {
6267 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006268 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6269 << ignoredFlag.toString() << flag.toString(),
6270 getLocationOfByte(ignoredFlag.getPosition()),
6271 /*IsStringLocation*/true,
6272 getSpecifierRange(startSpecifier, specifierLen),
6273 FixItHint::CreateRemoval(
6274 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006275}
6276
Ted Kremenek2b417712015-07-02 05:39:16 +00006277void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6278 unsigned flagLen) {
6279 // Warn about an empty flag.
6280 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6281 getLocationOfByte(startFlag),
6282 /*IsStringLocation*/true,
6283 getSpecifierRange(startFlag, flagLen));
6284}
6285
6286void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6287 unsigned flagLen) {
6288 // Warn about an invalid flag.
6289 auto Range = getSpecifierRange(startFlag, flagLen);
6290 StringRef flag(startFlag, flagLen);
6291 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6292 getLocationOfByte(startFlag),
6293 /*IsStringLocation*/true,
6294 Range, FixItHint::CreateRemoval(Range));
6295}
6296
6297void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6298 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6299 // Warn about using '[...]' without a '@' conversion.
6300 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6301 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6302 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6303 getLocationOfByte(conversionPosition),
6304 /*IsStringLocation*/true,
6305 Range, FixItHint::CreateRemoval(Range));
6306}
6307
Richard Smith55ce3522012-06-25 20:30:08 +00006308// Determines if the specified is a C++ class or struct containing
6309// a member with the specified name and kind (e.g. a CXXMethodDecl named
6310// "c_str()").
6311template<typename MemberKind>
6312static llvm::SmallPtrSet<MemberKind*, 1>
6313CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6314 const RecordType *RT = Ty->getAs<RecordType>();
6315 llvm::SmallPtrSet<MemberKind*, 1> Results;
6316
6317 if (!RT)
6318 return Results;
6319 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006320 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006321 return Results;
6322
Alp Tokerb6cc5922014-05-03 03:45:55 +00006323 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006324 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006325 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006326
6327 // We just need to include all members of the right kind turned up by the
6328 // filter, at this point.
6329 if (S.LookupQualifiedName(R, RT->getDecl()))
6330 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6331 NamedDecl *decl = (*I)->getUnderlyingDecl();
6332 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6333 Results.insert(FK);
6334 }
6335 return Results;
6336}
6337
Richard Smith2868a732014-02-28 01:36:39 +00006338/// Check if we could call '.c_str()' on an object.
6339///
6340/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6341/// allow the call, or if it would be ambiguous).
6342bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006343 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6344
Richard Smith2868a732014-02-28 01:36:39 +00006345 MethodSet Results =
6346 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6347 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6348 MI != ME; ++MI)
6349 if ((*MI)->getMinRequiredArguments() == 0)
6350 return true;
6351 return false;
6352}
6353
Richard Smith55ce3522012-06-25 20:30:08 +00006354// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006355// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006356// Returns true when a c_str() conversion method is found.
6357bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006358 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006359 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006360
6361 MethodSet Results =
6362 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6363
6364 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6365 MI != ME; ++MI) {
6366 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006367 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006368 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006369 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006370 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006371 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6372 << "c_str()"
6373 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6374 return true;
6375 }
6376 }
6377
6378 return false;
6379}
6380
Ted Kremenekab278de2010-01-28 23:39:18 +00006381bool
Ted Kremenek02087932010-07-16 02:11:22 +00006382CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006383 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006384 const char *startSpecifier,
6385 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006386 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006387 using namespace analyze_printf;
6388
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006389 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006390
Ted Kremenek6cd69422010-07-19 22:01:06 +00006391 if (FS.consumesDataArgument()) {
6392 if (atFirstArg) {
6393 atFirstArg = false;
6394 usesPositionalArgs = FS.usesPositionalArg();
6395 }
6396 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006397 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6398 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006399 return false;
6400 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006401 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006402
Ted Kremenekd1668192010-02-27 01:41:03 +00006403 // First check if the field width, precision, and conversion specifier
6404 // have matching data arguments.
6405 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6406 startSpecifier, specifierLen)) {
6407 return false;
6408 }
6409
6410 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6411 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006412 return false;
6413 }
6414
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006415 if (!CS.consumesDataArgument()) {
6416 // FIXME: Technically specifying a precision or field width here
6417 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006418 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006419 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006420
Ted Kremenek4a49d982010-02-26 19:18:41 +00006421 // Consume the argument.
6422 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006423 if (argIndex < NumDataArgs) {
6424 // The check to see if the argIndex is valid will come later.
6425 // We set the bit here because we may exit early from this
6426 // function if we encounter some other error.
6427 CoveredArgs.set(argIndex);
6428 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006429
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006430 // FreeBSD kernel extensions.
6431 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6432 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6433 // We need at least two arguments.
6434 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6435 return false;
6436
6437 // Claim the second argument.
6438 CoveredArgs.set(argIndex + 1);
6439
6440 // Type check the first argument (int for %b, pointer for %D)
6441 const Expr *Ex = getDataArg(argIndex);
6442 const analyze_printf::ArgType &AT =
6443 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6444 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6445 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6446 EmitFormatDiagnostic(
6447 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6448 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6449 << false << Ex->getSourceRange(),
6450 Ex->getLocStart(), /*IsStringLocation*/false,
6451 getSpecifierRange(startSpecifier, specifierLen));
6452
6453 // Type check the second argument (char * for both %b and %D)
6454 Ex = getDataArg(argIndex + 1);
6455 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6456 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6457 EmitFormatDiagnostic(
6458 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6459 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6460 << false << Ex->getSourceRange(),
6461 Ex->getLocStart(), /*IsStringLocation*/false,
6462 getSpecifierRange(startSpecifier, specifierLen));
6463
6464 return true;
6465 }
6466
Ted Kremenek4a49d982010-02-26 19:18:41 +00006467 // Check for using an Objective-C specific conversion specifier
6468 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006469 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006470 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6471 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006472 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006473
Mehdi Amini06d367c2016-10-24 20:39:34 +00006474 // %P can only be used with os_log.
6475 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6476 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6477 specifierLen);
6478 }
6479
6480 // %n is not allowed with os_log.
6481 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6482 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6483 getLocationOfByte(CS.getStart()),
6484 /*IsStringLocation*/ false,
6485 getSpecifierRange(startSpecifier, specifierLen));
6486
6487 return true;
6488 }
6489
6490 // Only scalars are allowed for os_trace.
6491 if (FSType == Sema::FST_OSTrace &&
6492 (CS.getKind() == ConversionSpecifier::PArg ||
6493 CS.getKind() == ConversionSpecifier::sArg ||
6494 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6495 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6496 specifierLen);
6497 }
6498
6499 // Check for use of public/private annotation outside of os_log().
6500 if (FSType != Sema::FST_OSLog) {
6501 if (FS.isPublic().isSet()) {
6502 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6503 << "public",
6504 getLocationOfByte(FS.isPublic().getPosition()),
6505 /*IsStringLocation*/ false,
6506 getSpecifierRange(startSpecifier, specifierLen));
6507 }
6508 if (FS.isPrivate().isSet()) {
6509 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6510 << "private",
6511 getLocationOfByte(FS.isPrivate().getPosition()),
6512 /*IsStringLocation*/ false,
6513 getSpecifierRange(startSpecifier, specifierLen));
6514 }
6515 }
6516
Tom Careb49ec692010-06-17 19:00:27 +00006517 // Check for invalid use of field width
6518 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006519 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006520 startSpecifier, specifierLen);
6521 }
6522
6523 // Check for invalid use of precision
6524 if (!FS.hasValidPrecision()) {
6525 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6526 startSpecifier, specifierLen);
6527 }
6528
Mehdi Amini06d367c2016-10-24 20:39:34 +00006529 // Precision is mandatory for %P specifier.
6530 if (CS.getKind() == ConversionSpecifier::PArg &&
6531 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6532 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6533 getLocationOfByte(startSpecifier),
6534 /*IsStringLocation*/ false,
6535 getSpecifierRange(startSpecifier, specifierLen));
6536 }
6537
Tom Careb49ec692010-06-17 19:00:27 +00006538 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006539 if (!FS.hasValidThousandsGroupingPrefix())
6540 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006541 if (!FS.hasValidLeadingZeros())
6542 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6543 if (!FS.hasValidPlusPrefix())
6544 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006545 if (!FS.hasValidSpacePrefix())
6546 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006547 if (!FS.hasValidAlternativeForm())
6548 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6549 if (!FS.hasValidLeftJustified())
6550 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6551
6552 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006553 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6554 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6555 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006556 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6557 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6558 startSpecifier, specifierLen);
6559
6560 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006561 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006562 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6563 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006564 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006565 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006566 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006567 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6568 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006569
Jordan Rose92303592012-09-08 04:00:03 +00006570 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6571 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6572
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006573 // The remaining checks depend on the data arguments.
6574 if (HasVAListArg)
6575 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006576
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006577 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006578 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006579
Jordan Rose58bbe422012-07-19 18:10:08 +00006580 const Expr *Arg = getDataArg(argIndex);
6581 if (!Arg)
6582 return true;
6583
6584 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006585}
6586
Jordan Roseaee34382012-09-05 22:56:26 +00006587static bool requiresParensToAddCast(const Expr *E) {
6588 // FIXME: We should have a general way to reason about operator
6589 // precedence and whether parens are actually needed here.
6590 // Take care of a few common cases where they aren't.
6591 const Expr *Inside = E->IgnoreImpCasts();
6592 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6593 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6594
6595 switch (Inside->getStmtClass()) {
6596 case Stmt::ArraySubscriptExprClass:
6597 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006598 case Stmt::CharacterLiteralClass:
6599 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006600 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006601 case Stmt::FloatingLiteralClass:
6602 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006603 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006604 case Stmt::ObjCArrayLiteralClass:
6605 case Stmt::ObjCBoolLiteralExprClass:
6606 case Stmt::ObjCBoxedExprClass:
6607 case Stmt::ObjCDictionaryLiteralClass:
6608 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006609 case Stmt::ObjCIvarRefExprClass:
6610 case Stmt::ObjCMessageExprClass:
6611 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006612 case Stmt::ObjCStringLiteralClass:
6613 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006614 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006615 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006616 case Stmt::UnaryOperatorClass:
6617 return false;
6618 default:
6619 return true;
6620 }
6621}
6622
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006623static std::pair<QualType, StringRef>
6624shouldNotPrintDirectly(const ASTContext &Context,
6625 QualType IntendedTy,
6626 const Expr *E) {
6627 // Use a 'while' to peel off layers of typedefs.
6628 QualType TyTy = IntendedTy;
6629 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6630 StringRef Name = UserTy->getDecl()->getName();
6631 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006632 .Case("CFIndex", Context.getNSIntegerType())
6633 .Case("NSInteger", Context.getNSIntegerType())
6634 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006635 .Case("SInt32", Context.IntTy)
6636 .Case("UInt32", Context.UnsignedIntTy)
6637 .Default(QualType());
6638
6639 if (!CastTy.isNull())
6640 return std::make_pair(CastTy, Name);
6641
6642 TyTy = UserTy->desugar();
6643 }
6644
6645 // Strip parens if necessary.
6646 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6647 return shouldNotPrintDirectly(Context,
6648 PE->getSubExpr()->getType(),
6649 PE->getSubExpr());
6650
6651 // If this is a conditional expression, then its result type is constructed
6652 // via usual arithmetic conversions and thus there might be no necessary
6653 // typedef sugar there. Recurse to operands to check for NSInteger &
6654 // Co. usage condition.
6655 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6656 QualType TrueTy, FalseTy;
6657 StringRef TrueName, FalseName;
6658
6659 std::tie(TrueTy, TrueName) =
6660 shouldNotPrintDirectly(Context,
6661 CO->getTrueExpr()->getType(),
6662 CO->getTrueExpr());
6663 std::tie(FalseTy, FalseName) =
6664 shouldNotPrintDirectly(Context,
6665 CO->getFalseExpr()->getType(),
6666 CO->getFalseExpr());
6667
6668 if (TrueTy == FalseTy)
6669 return std::make_pair(TrueTy, TrueName);
6670 else if (TrueTy.isNull())
6671 return std::make_pair(FalseTy, FalseName);
6672 else if (FalseTy.isNull())
6673 return std::make_pair(TrueTy, TrueName);
6674 }
6675
6676 return std::make_pair(QualType(), StringRef());
6677}
6678
Richard Smith55ce3522012-06-25 20:30:08 +00006679bool
6680CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6681 const char *StartSpecifier,
6682 unsigned SpecifierLen,
6683 const Expr *E) {
6684 using namespace analyze_format_string;
6685 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006686
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006687 // Now type check the data expression that matches the
6688 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006689 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006690 if (!AT.isValid())
6691 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006692
Jordan Rose598ec092012-12-05 18:44:40 +00006693 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006694 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6695 ExprTy = TET->getUnderlyingExpr()->getType();
6696 }
6697
Seth Cantrellb4802962015-03-04 03:12:10 +00006698 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6699
6700 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006701 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006702 }
Jordan Rose98709982012-06-04 22:48:57 +00006703
Jordan Rose22b74712012-09-05 22:56:19 +00006704 // Look through argument promotions for our error message's reported type.
6705 // This includes the integral and floating promotions, but excludes array
6706 // and function pointer decay; seeing that an argument intended to be a
6707 // string has type 'char [6]' is probably more confusing than 'char *'.
6708 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6709 if (ICE->getCastKind() == CK_IntegralCast ||
6710 ICE->getCastKind() == CK_FloatingCast) {
6711 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006712 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006713
6714 // Check if we didn't match because of an implicit cast from a 'char'
6715 // or 'short' to an 'int'. This is done because printf is a varargs
6716 // function.
6717 if (ICE->getType() == S.Context.IntTy ||
6718 ICE->getType() == S.Context.UnsignedIntTy) {
6719 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006720 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006721 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006722 }
Jordan Rose98709982012-06-04 22:48:57 +00006723 }
Jordan Rose598ec092012-12-05 18:44:40 +00006724 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6725 // Special case for 'a', which has type 'int' in C.
6726 // Note, however, that we do /not/ want to treat multibyte constants like
6727 // 'MooV' as characters! This form is deprecated but still exists.
6728 if (ExprTy == S.Context.IntTy)
6729 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6730 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006731 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006732
Jordan Rosebc53ed12014-05-31 04:12:14 +00006733 // Look through enums to their underlying type.
6734 bool IsEnum = false;
6735 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6736 ExprTy = EnumTy->getDecl()->getIntegerType();
6737 IsEnum = true;
6738 }
6739
Jordan Rose0e5badd2012-12-05 18:44:49 +00006740 // %C in an Objective-C context prints a unichar, not a wchar_t.
6741 // If the argument is an integer of some kind, believe the %C and suggest
6742 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006743 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006744 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006745 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6746 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6747 !ExprTy->isCharType()) {
6748 // 'unichar' is defined as a typedef of unsigned short, but we should
6749 // prefer using the typedef if it is visible.
6750 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006751
6752 // While we are here, check if the value is an IntegerLiteral that happens
6753 // to be within the valid range.
6754 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6755 const llvm::APInt &V = IL->getValue();
6756 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6757 return true;
6758 }
6759
Jordan Rose0e5badd2012-12-05 18:44:49 +00006760 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6761 Sema::LookupOrdinaryName);
6762 if (S.LookupName(Result, S.getCurScope())) {
6763 NamedDecl *ND = Result.getFoundDecl();
6764 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6765 if (TD->getUnderlyingType() == IntendedTy)
6766 IntendedTy = S.Context.getTypedefType(TD);
6767 }
6768 }
6769 }
6770
6771 // Special-case some of Darwin's platform-independence types by suggesting
6772 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006773 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006774 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006775 QualType CastTy;
6776 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6777 if (!CastTy.isNull()) {
6778 IntendedTy = CastTy;
6779 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006780 }
6781 }
6782
Jordan Rose22b74712012-09-05 22:56:19 +00006783 // We may be able to offer a FixItHint if it is a supported type.
6784 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006785 bool success =
6786 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006787
Jordan Rose22b74712012-09-05 22:56:19 +00006788 if (success) {
6789 // Get the fix string from the fixed format specifier
6790 SmallString<16> buf;
6791 llvm::raw_svector_ostream os(buf);
6792 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006793
Jordan Roseaee34382012-09-05 22:56:26 +00006794 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6795
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006796 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006797 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6798 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6799 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6800 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006801 // In this case, the specifier is wrong and should be changed to match
6802 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006803 EmitFormatDiagnostic(S.PDiag(diag)
6804 << AT.getRepresentativeTypeName(S.Context)
6805 << IntendedTy << IsEnum << E->getSourceRange(),
6806 E->getLocStart(),
6807 /*IsStringLocation*/ false, SpecRange,
6808 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006809 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006810 // The canonical type for formatting this value is different from the
6811 // actual type of the expression. (This occurs, for example, with Darwin's
6812 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6813 // should be printed as 'long' for 64-bit compatibility.)
6814 // Rather than emitting a normal format/argument mismatch, we want to
6815 // add a cast to the recommended type (and correct the format string
6816 // if necessary).
6817 SmallString<16> CastBuf;
6818 llvm::raw_svector_ostream CastFix(CastBuf);
6819 CastFix << "(";
6820 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6821 CastFix << ")";
6822
6823 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006824 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006825 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6826
6827 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6828 // If there's already a cast present, just replace it.
6829 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6830 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6831
6832 } else if (!requiresParensToAddCast(E)) {
6833 // If the expression has high enough precedence,
6834 // just write the C-style cast.
6835 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6836 CastFix.str()));
6837 } else {
6838 // Otherwise, add parens around the expression as well as the cast.
6839 CastFix << "(";
6840 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6841 CastFix.str()));
6842
Alp Tokerb6cc5922014-05-03 03:45:55 +00006843 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006844 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6845 }
6846
Jordan Rose0e5badd2012-12-05 18:44:49 +00006847 if (ShouldNotPrintDirectly) {
6848 // The expression has a type that should not be printed directly.
6849 // We extract the name from the typedef because we don't want to show
6850 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006851 StringRef Name;
6852 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6853 Name = TypedefTy->getDecl()->getName();
6854 else
6855 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006856 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006857 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006858 << E->getSourceRange(),
6859 E->getLocStart(), /*IsStringLocation=*/false,
6860 SpecRange, Hints);
6861 } else {
6862 // In this case, the expression could be printed using a different
6863 // specifier, but we've decided that the specifier is probably correct
6864 // and we should cast instead. Just use the normal warning message.
6865 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006866 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6867 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006868 << E->getSourceRange(),
6869 E->getLocStart(), /*IsStringLocation*/false,
6870 SpecRange, Hints);
6871 }
Jordan Roseaee34382012-09-05 22:56:26 +00006872 }
Jordan Rose22b74712012-09-05 22:56:19 +00006873 } else {
6874 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6875 SpecifierLen);
6876 // Since the warning for passing non-POD types to variadic functions
6877 // was deferred until now, we emit a warning for non-POD
6878 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006879 switch (S.isValidVarArgType(ExprTy)) {
6880 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006881 case Sema::VAK_ValidInCXX11: {
6882 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6883 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6884 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6885 }
Richard Smithd7293d72013-08-05 18:49:43 +00006886
Seth Cantrellb4802962015-03-04 03:12:10 +00006887 EmitFormatDiagnostic(
6888 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6889 << IsEnum << CSR << E->getSourceRange(),
6890 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6891 break;
6892 }
Richard Smithd7293d72013-08-05 18:49:43 +00006893 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006894 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006895 EmitFormatDiagnostic(
6896 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006897 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006898 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006899 << CallType
6900 << AT.getRepresentativeTypeName(S.Context)
6901 << CSR
6902 << E->getSourceRange(),
6903 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006904 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006905 break;
6906
6907 case Sema::VAK_Invalid:
6908 if (ExprTy->isObjCObjectType())
6909 EmitFormatDiagnostic(
6910 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6911 << S.getLangOpts().CPlusPlus11
6912 << ExprTy
6913 << CallType
6914 << AT.getRepresentativeTypeName(S.Context)
6915 << CSR
6916 << E->getSourceRange(),
6917 E->getLocStart(), /*IsStringLocation*/false, CSR);
6918 else
6919 // FIXME: If this is an initializer list, suggest removing the braces
6920 // or inserting a cast to the target type.
6921 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6922 << isa<InitListExpr>(E) << ExprTy << CallType
6923 << AT.getRepresentativeTypeName(S.Context)
6924 << E->getSourceRange();
6925 break;
6926 }
6927
6928 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6929 "format string specifier index out of range");
6930 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006931 }
6932
Ted Kremenekab278de2010-01-28 23:39:18 +00006933 return true;
6934}
6935
Ted Kremenek02087932010-07-16 02:11:22 +00006936//===--- CHECK: Scanf format string checking ------------------------------===//
6937
6938namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006939
Ted Kremenek02087932010-07-16 02:11:22 +00006940class CheckScanfHandler : public CheckFormatHandler {
6941public:
Stephen Hines648c3692016-09-16 01:07:04 +00006942 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006943 const Expr *origFormatExpr, Sema::FormatStringType type,
6944 unsigned firstDataArg, unsigned numDataArgs,
6945 const char *beg, bool hasVAListArg,
6946 ArrayRef<const Expr *> Args, unsigned formatIdx,
6947 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006948 llvm::SmallBitVector &CheckedVarArgs,
6949 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006950 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6951 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6952 inFunctionCall, CallType, CheckedVarArgs,
6953 UncoveredArg) {}
6954
Ted Kremenek02087932010-07-16 02:11:22 +00006955 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6956 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006957 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006958
6959 bool HandleInvalidScanfConversionSpecifier(
6960 const analyze_scanf::ScanfSpecifier &FS,
6961 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006962 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006963
Craig Toppere14c0f82014-03-12 04:55:44 +00006964 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006965};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006966
6967} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006968
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006969void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6970 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006971 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6972 getLocationOfByte(end), /*IsStringLocation*/true,
6973 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006974}
6975
Ted Kremenekce815422010-07-19 21:25:57 +00006976bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6977 const analyze_scanf::ScanfSpecifier &FS,
6978 const char *startSpecifier,
6979 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006980 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006981 FS.getConversionSpecifier();
6982
6983 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6984 getLocationOfByte(CS.getStart()),
6985 startSpecifier, specifierLen,
6986 CS.getStart(), CS.getLength());
6987}
6988
Ted Kremenek02087932010-07-16 02:11:22 +00006989bool CheckScanfHandler::HandleScanfSpecifier(
6990 const analyze_scanf::ScanfSpecifier &FS,
6991 const char *startSpecifier,
6992 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006993 using namespace analyze_scanf;
6994 using namespace analyze_format_string;
6995
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006996 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006997
Ted Kremenek6cd69422010-07-19 22:01:06 +00006998 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6999 // be used to decide if we are using positional arguments consistently.
7000 if (FS.consumesDataArgument()) {
7001 if (atFirstArg) {
7002 atFirstArg = false;
7003 usesPositionalArgs = FS.usesPositionalArg();
7004 }
7005 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007006 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7007 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007008 return false;
7009 }
Ted Kremenek02087932010-07-16 02:11:22 +00007010 }
7011
7012 // Check if the field with is non-zero.
7013 const OptionalAmount &Amt = FS.getFieldWidth();
7014 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7015 if (Amt.getConstantAmount() == 0) {
7016 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7017 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00007018 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7019 getLocationOfByte(Amt.getStart()),
7020 /*IsStringLocation*/true, R,
7021 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00007022 }
7023 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007024
Ted Kremenek02087932010-07-16 02:11:22 +00007025 if (!FS.consumesDataArgument()) {
7026 // FIXME: Technically specifying a precision or field width here
7027 // makes no sense. Worth issuing a warning at some point.
7028 return true;
7029 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007030
Ted Kremenek02087932010-07-16 02:11:22 +00007031 // Consume the argument.
7032 unsigned argIndex = FS.getArgIndex();
7033 if (argIndex < NumDataArgs) {
7034 // The check to see if the argIndex is valid will come later.
7035 // We set the bit here because we may exit early from this
7036 // function if we encounter some other error.
7037 CoveredArgs.set(argIndex);
7038 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007039
Ted Kremenek4407ea42010-07-20 20:04:47 +00007040 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007041 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007042 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7043 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007044 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007045 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007046 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007047 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7048 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007049
Jordan Rose92303592012-09-08 04:00:03 +00007050 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7051 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7052
Ted Kremenek02087932010-07-16 02:11:22 +00007053 // The remaining checks depend on the data arguments.
7054 if (HasVAListArg)
7055 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007056
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007057 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00007058 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00007059
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007060 // Check that the argument type matches the format specifier.
7061 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007062 if (!Ex)
7063 return true;
7064
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00007065 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00007066
7067 if (!AT.isValid()) {
7068 return true;
7069 }
7070
Seth Cantrellb4802962015-03-04 03:12:10 +00007071 analyze_format_string::ArgType::MatchKind match =
7072 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00007073 if (match == analyze_format_string::ArgType::Match) {
7074 return true;
7075 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007076
Seth Cantrell79340072015-03-04 05:58:08 +00007077 ScanfSpecifier fixedFS = FS;
7078 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7079 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007080
Seth Cantrell79340072015-03-04 05:58:08 +00007081 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7082 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7083 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7084 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007085
Seth Cantrell79340072015-03-04 05:58:08 +00007086 if (success) {
7087 // Get the fix string from the fixed format specifier.
7088 SmallString<128> buf;
7089 llvm::raw_svector_ostream os(buf);
7090 fixedFS.toString(os);
7091
7092 EmitFormatDiagnostic(
7093 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7094 << Ex->getType() << false << Ex->getSourceRange(),
7095 Ex->getLocStart(),
7096 /*IsStringLocation*/ false,
7097 getSpecifierRange(startSpecifier, specifierLen),
7098 FixItHint::CreateReplacement(
7099 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7100 } else {
7101 EmitFormatDiagnostic(S.PDiag(diag)
7102 << AT.getRepresentativeTypeName(S.Context)
7103 << Ex->getType() << false << Ex->getSourceRange(),
7104 Ex->getLocStart(),
7105 /*IsStringLocation*/ false,
7106 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007107 }
7108
Ted Kremenek02087932010-07-16 02:11:22 +00007109 return true;
7110}
7111
Stephen Hines648c3692016-09-16 01:07:04 +00007112static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007113 const Expr *OrigFormatExpr,
7114 ArrayRef<const Expr *> Args,
7115 bool HasVAListArg, unsigned format_idx,
7116 unsigned firstDataArg,
7117 Sema::FormatStringType Type,
7118 bool inFunctionCall,
7119 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007120 llvm::SmallBitVector &CheckedVarArgs,
7121 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007122 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007123 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007124 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007125 S, inFunctionCall, Args[format_idx],
7126 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007127 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007128 return;
7129 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007130
Ted Kremenekab278de2010-01-28 23:39:18 +00007131 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007132 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007133 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007134 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007135 const ConstantArrayType *T =
7136 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007137 assert(T && "String literal not of constant array type!");
7138 size_t TypeSize = T->getSize().getZExtValue();
7139 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007140 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007141
7142 // Emit a warning if the string literal is truncated and does not contain an
7143 // embedded null character.
7144 if (TypeSize <= StrRef.size() &&
7145 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7146 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007147 S, inFunctionCall, Args[format_idx],
7148 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007149 FExpr->getLocStart(),
7150 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7151 return;
7152 }
7153
Ted Kremenekab278de2010-01-28 23:39:18 +00007154 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007155 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007156 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007157 S, inFunctionCall, Args[format_idx],
7158 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007159 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007160 return;
7161 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007162
7163 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007164 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7165 Type == Sema::FST_OSTrace) {
7166 CheckPrintfHandler H(
7167 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7168 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7169 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7170 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007171
Hans Wennborg23926bd2011-12-15 10:25:47 +00007172 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007173 S.getLangOpts(),
7174 S.Context.getTargetInfo(),
7175 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007176 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007177 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007178 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7179 numDataArgs, Str, HasVAListArg, Args, format_idx,
7180 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007181
Hans Wennborg23926bd2011-12-15 10:25:47 +00007182 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007183 S.getLangOpts(),
7184 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007185 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007186 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007187}
7188
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007189bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7190 // Str - The format string. NOTE: this is NOT null-terminated!
7191 StringRef StrRef = FExpr->getString();
7192 const char *Str = StrRef.data();
7193 // Account for cases where the string literal is truncated in a declaration.
7194 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7195 assert(T && "String literal not of constant array type!");
7196 size_t TypeSize = T->getSize().getZExtValue();
7197 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7198 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7199 getLangOpts(),
7200 Context.getTargetInfo());
7201}
7202
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007203//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7204
7205// Returns the related absolute value function that is larger, of 0 if one
7206// does not exist.
7207static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7208 switch (AbsFunction) {
7209 default:
7210 return 0;
7211
7212 case Builtin::BI__builtin_abs:
7213 return Builtin::BI__builtin_labs;
7214 case Builtin::BI__builtin_labs:
7215 return Builtin::BI__builtin_llabs;
7216 case Builtin::BI__builtin_llabs:
7217 return 0;
7218
7219 case Builtin::BI__builtin_fabsf:
7220 return Builtin::BI__builtin_fabs;
7221 case Builtin::BI__builtin_fabs:
7222 return Builtin::BI__builtin_fabsl;
7223 case Builtin::BI__builtin_fabsl:
7224 return 0;
7225
7226 case Builtin::BI__builtin_cabsf:
7227 return Builtin::BI__builtin_cabs;
7228 case Builtin::BI__builtin_cabs:
7229 return Builtin::BI__builtin_cabsl;
7230 case Builtin::BI__builtin_cabsl:
7231 return 0;
7232
7233 case Builtin::BIabs:
7234 return Builtin::BIlabs;
7235 case Builtin::BIlabs:
7236 return Builtin::BIllabs;
7237 case Builtin::BIllabs:
7238 return 0;
7239
7240 case Builtin::BIfabsf:
7241 return Builtin::BIfabs;
7242 case Builtin::BIfabs:
7243 return Builtin::BIfabsl;
7244 case Builtin::BIfabsl:
7245 return 0;
7246
7247 case Builtin::BIcabsf:
7248 return Builtin::BIcabs;
7249 case Builtin::BIcabs:
7250 return Builtin::BIcabsl;
7251 case Builtin::BIcabsl:
7252 return 0;
7253 }
7254}
7255
7256// Returns the argument type of the absolute value function.
7257static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7258 unsigned AbsType) {
7259 if (AbsType == 0)
7260 return QualType();
7261
7262 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7263 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7264 if (Error != ASTContext::GE_None)
7265 return QualType();
7266
7267 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7268 if (!FT)
7269 return QualType();
7270
7271 if (FT->getNumParams() != 1)
7272 return QualType();
7273
7274 return FT->getParamType(0);
7275}
7276
7277// Returns the best absolute value function, or zero, based on type and
7278// current absolute value function.
7279static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7280 unsigned AbsFunctionKind) {
7281 unsigned BestKind = 0;
7282 uint64_t ArgSize = Context.getTypeSize(ArgType);
7283 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7284 Kind = getLargerAbsoluteValueFunction(Kind)) {
7285 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7286 if (Context.getTypeSize(ParamType) >= ArgSize) {
7287 if (BestKind == 0)
7288 BestKind = Kind;
7289 else if (Context.hasSameType(ParamType, ArgType)) {
7290 BestKind = Kind;
7291 break;
7292 }
7293 }
7294 }
7295 return BestKind;
7296}
7297
7298enum AbsoluteValueKind {
7299 AVK_Integer,
7300 AVK_Floating,
7301 AVK_Complex
7302};
7303
7304static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7305 if (T->isIntegralOrEnumerationType())
7306 return AVK_Integer;
7307 if (T->isRealFloatingType())
7308 return AVK_Floating;
7309 if (T->isAnyComplexType())
7310 return AVK_Complex;
7311
7312 llvm_unreachable("Type not integer, floating, or complex");
7313}
7314
7315// Changes the absolute value function to a different type. Preserves whether
7316// the function is a builtin.
7317static unsigned changeAbsFunction(unsigned AbsKind,
7318 AbsoluteValueKind ValueKind) {
7319 switch (ValueKind) {
7320 case AVK_Integer:
7321 switch (AbsKind) {
7322 default:
7323 return 0;
7324 case Builtin::BI__builtin_fabsf:
7325 case Builtin::BI__builtin_fabs:
7326 case Builtin::BI__builtin_fabsl:
7327 case Builtin::BI__builtin_cabsf:
7328 case Builtin::BI__builtin_cabs:
7329 case Builtin::BI__builtin_cabsl:
7330 return Builtin::BI__builtin_abs;
7331 case Builtin::BIfabsf:
7332 case Builtin::BIfabs:
7333 case Builtin::BIfabsl:
7334 case Builtin::BIcabsf:
7335 case Builtin::BIcabs:
7336 case Builtin::BIcabsl:
7337 return Builtin::BIabs;
7338 }
7339 case AVK_Floating:
7340 switch (AbsKind) {
7341 default:
7342 return 0;
7343 case Builtin::BI__builtin_abs:
7344 case Builtin::BI__builtin_labs:
7345 case Builtin::BI__builtin_llabs:
7346 case Builtin::BI__builtin_cabsf:
7347 case Builtin::BI__builtin_cabs:
7348 case Builtin::BI__builtin_cabsl:
7349 return Builtin::BI__builtin_fabsf;
7350 case Builtin::BIabs:
7351 case Builtin::BIlabs:
7352 case Builtin::BIllabs:
7353 case Builtin::BIcabsf:
7354 case Builtin::BIcabs:
7355 case Builtin::BIcabsl:
7356 return Builtin::BIfabsf;
7357 }
7358 case AVK_Complex:
7359 switch (AbsKind) {
7360 default:
7361 return 0;
7362 case Builtin::BI__builtin_abs:
7363 case Builtin::BI__builtin_labs:
7364 case Builtin::BI__builtin_llabs:
7365 case Builtin::BI__builtin_fabsf:
7366 case Builtin::BI__builtin_fabs:
7367 case Builtin::BI__builtin_fabsl:
7368 return Builtin::BI__builtin_cabsf;
7369 case Builtin::BIabs:
7370 case Builtin::BIlabs:
7371 case Builtin::BIllabs:
7372 case Builtin::BIfabsf:
7373 case Builtin::BIfabs:
7374 case Builtin::BIfabsl:
7375 return Builtin::BIcabsf;
7376 }
7377 }
7378 llvm_unreachable("Unable to convert function");
7379}
7380
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007381static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007382 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7383 if (!FnInfo)
7384 return 0;
7385
7386 switch (FDecl->getBuiltinID()) {
7387 default:
7388 return 0;
7389 case Builtin::BI__builtin_abs:
7390 case Builtin::BI__builtin_fabs:
7391 case Builtin::BI__builtin_fabsf:
7392 case Builtin::BI__builtin_fabsl:
7393 case Builtin::BI__builtin_labs:
7394 case Builtin::BI__builtin_llabs:
7395 case Builtin::BI__builtin_cabs:
7396 case Builtin::BI__builtin_cabsf:
7397 case Builtin::BI__builtin_cabsl:
7398 case Builtin::BIabs:
7399 case Builtin::BIlabs:
7400 case Builtin::BIllabs:
7401 case Builtin::BIfabs:
7402 case Builtin::BIfabsf:
7403 case Builtin::BIfabsl:
7404 case Builtin::BIcabs:
7405 case Builtin::BIcabsf:
7406 case Builtin::BIcabsl:
7407 return FDecl->getBuiltinID();
7408 }
7409 llvm_unreachable("Unknown Builtin type");
7410}
7411
7412// If the replacement is valid, emit a note with replacement function.
7413// Additionally, suggest including the proper header if not already included.
7414static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007415 unsigned AbsKind, QualType ArgType) {
7416 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007417 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007418 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007419 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7420 FunctionName = "std::abs";
7421 if (ArgType->isIntegralOrEnumerationType()) {
7422 HeaderName = "cstdlib";
7423 } else if (ArgType->isRealFloatingType()) {
7424 HeaderName = "cmath";
7425 } else {
7426 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007427 }
Richard Trieubeffb832014-04-15 23:47:53 +00007428
7429 // Lookup all std::abs
7430 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007431 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007432 R.suppressDiagnostics();
7433 S.LookupQualifiedName(R, Std);
7434
7435 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007436 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007437 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7438 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7439 } else {
7440 FDecl = dyn_cast<FunctionDecl>(I);
7441 }
7442 if (!FDecl)
7443 continue;
7444
7445 // Found std::abs(), check that they are the right ones.
7446 if (FDecl->getNumParams() != 1)
7447 continue;
7448
7449 // Check that the parameter type can handle the argument.
7450 QualType ParamType = FDecl->getParamDecl(0)->getType();
7451 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7452 S.Context.getTypeSize(ArgType) <=
7453 S.Context.getTypeSize(ParamType)) {
7454 // Found a function, don't need the header hint.
7455 EmitHeaderHint = false;
7456 break;
7457 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007458 }
Richard Trieubeffb832014-04-15 23:47:53 +00007459 }
7460 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007461 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007462 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7463
7464 if (HeaderName) {
7465 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7466 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7467 R.suppressDiagnostics();
7468 S.LookupName(R, S.getCurScope());
7469
7470 if (R.isSingleResult()) {
7471 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7472 if (FD && FD->getBuiltinID() == AbsKind) {
7473 EmitHeaderHint = false;
7474 } else {
7475 return;
7476 }
7477 } else if (!R.empty()) {
7478 return;
7479 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007480 }
7481 }
7482
7483 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007484 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007485
Richard Trieubeffb832014-04-15 23:47:53 +00007486 if (!HeaderName)
7487 return;
7488
7489 if (!EmitHeaderHint)
7490 return;
7491
Alp Toker5d96e0a2014-07-11 20:53:51 +00007492 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7493 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007494}
7495
Richard Trieua7f30b12016-12-06 01:42:28 +00007496template <std::size_t StrLen>
7497static bool IsStdFunction(const FunctionDecl *FDecl,
7498 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007499 if (!FDecl)
7500 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007501 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007502 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007503 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007504 return false;
7505
7506 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007507}
7508
7509// Warn when using the wrong abs() function.
7510void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007511 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007512 if (Call->getNumArgs() != 1)
7513 return;
7514
7515 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007516 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007517 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007518 return;
7519
7520 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7521 QualType ParamType = Call->getArg(0)->getType();
7522
Alp Toker5d96e0a2014-07-11 20:53:51 +00007523 // Unsigned types cannot be negative. Suggest removing the absolute value
7524 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007525 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007526 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007527 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007528 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7529 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007530 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007531 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7532 return;
7533 }
7534
David Majnemer7f77eb92015-11-15 03:04:34 +00007535 // Taking the absolute value of a pointer is very suspicious, they probably
7536 // wanted to index into an array, dereference a pointer, call a function, etc.
7537 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7538 unsigned DiagType = 0;
7539 if (ArgType->isFunctionType())
7540 DiagType = 1;
7541 else if (ArgType->isArrayType())
7542 DiagType = 2;
7543
7544 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7545 return;
7546 }
7547
Richard Trieubeffb832014-04-15 23:47:53 +00007548 // std::abs has overloads which prevent most of the absolute value problems
7549 // from occurring.
7550 if (IsStdAbs)
7551 return;
7552
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007553 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7554 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7555
7556 // The argument and parameter are the same kind. Check if they are the right
7557 // size.
7558 if (ArgValueKind == ParamValueKind) {
7559 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7560 return;
7561
7562 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7563 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7564 << FDecl << ArgType << ParamType;
7565
7566 if (NewAbsKind == 0)
7567 return;
7568
7569 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007570 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007571 return;
7572 }
7573
7574 // ArgValueKind != ParamValueKind
7575 // The wrong type of absolute value function was used. Attempt to find the
7576 // proper one.
7577 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7578 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7579 if (NewAbsKind == 0)
7580 return;
7581
7582 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7583 << FDecl << ParamValueKind << ArgValueKind;
7584
7585 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007586 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007587}
7588
Richard Trieu67c00712016-12-05 23:41:46 +00007589//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007590void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7591 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007592 if (!Call || !FDecl) return;
7593
7594 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007595 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007596 if (Call->getExprLoc().isMacroID()) return;
7597
7598 // Only care about the one template argument, two function parameter std::max
7599 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007600 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007601 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7602 if (!ArgList) return;
7603 if (ArgList->size() != 1) return;
7604
7605 // Check that template type argument is unsigned integer.
7606 const auto& TA = ArgList->get(0);
7607 if (TA.getKind() != TemplateArgument::Type) return;
7608 QualType ArgType = TA.getAsType();
7609 if (!ArgType->isUnsignedIntegerType()) return;
7610
7611 // See if either argument is a literal zero.
7612 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7613 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7614 if (!MTE) return false;
7615 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7616 if (!Num) return false;
7617 if (Num->getValue() != 0) return false;
7618 return true;
7619 };
7620
7621 const Expr *FirstArg = Call->getArg(0);
7622 const Expr *SecondArg = Call->getArg(1);
7623 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7624 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7625
7626 // Only warn when exactly one argument is zero.
7627 if (IsFirstArgZero == IsSecondArgZero) return;
7628
7629 SourceRange FirstRange = FirstArg->getSourceRange();
7630 SourceRange SecondRange = SecondArg->getSourceRange();
7631
7632 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7633
7634 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7635 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7636
7637 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7638 SourceRange RemovalRange;
7639 if (IsFirstArgZero) {
7640 RemovalRange = SourceRange(FirstRange.getBegin(),
7641 SecondRange.getBegin().getLocWithOffset(-1));
7642 } else {
7643 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7644 SecondRange.getEnd());
7645 }
7646
7647 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7648 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7649 << FixItHint::CreateRemoval(RemovalRange);
7650}
7651
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007652//===--- CHECK: Standard memory functions ---------------------------------===//
7653
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007654/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007655/// such as memcmp, strncat, etc and warns if it's a comparison.
7656///
7657/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7658static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7659 IdentifierInfo *FnName,
7660 SourceLocation FnLoc,
7661 SourceLocation RParenLoc) {
7662 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7663 if (!Size)
7664 return false;
7665
Richard Smithc70f1d62017-12-14 15:16:18 +00007666 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7667 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007668 return false;
7669
Nico Weber0e6daef2013-12-26 23:38:39 +00007670 SourceRange SizeRange = Size->getSourceRange();
7671 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7672 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007673 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007674 << FnName << FixItHint::CreateInsertion(
7675 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007676 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007677 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007678 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007679 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7680 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007681
7682 return true;
7683}
7684
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007685/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007686/// (e.g., whether it has a vtable).
7687static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7688 bool &IsContained) {
7689 // Look through array types while ignoring qualifiers.
7690 const Type *Ty = T->getBaseElementTypeUnsafe();
7691 IsContained = false;
7692
7693 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7694 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007695 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007696 return nullptr;
7697
7698 if (RD->isDynamicClass())
7699 return RD;
7700
7701 // Check all the fields. If any bases were dynamic, the class is dynamic.
7702 // It's impossible for a class to transitively contain itself by value, so
7703 // infinite recursion is impossible.
7704 for (auto *FD : RD->fields()) {
7705 bool SubContained;
7706 if (const CXXRecordDecl *ContainedRD =
7707 getContainedDynamicClass(FD->getType(), SubContained)) {
7708 IsContained = true;
7709 return ContainedRD;
7710 }
7711 }
7712
7713 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007714}
7715
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007716/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007717/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007718static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007719 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007720 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007721 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007722 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007723
Craig Topperc3ec1492014-05-26 06:22:03 +00007724 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007725}
7726
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007727/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007728static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007729 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7730 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007731 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007732 return SizeOf->getTypeOfArgument();
7733
7734 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007735}
7736
Akira Hatanaka2be04412018-04-17 19:13:41 +00007737namespace {
7738
7739struct SearchNonTrivialToInitializeField
7740 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7741 using Super =
7742 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7743
7744 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7745
7746 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7747 SourceLocation SL) {
7748 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7749 asDerived().visitArray(PDIK, AT, SL);
7750 return;
7751 }
7752
7753 Super::visitWithKind(PDIK, FT, SL);
7754 }
7755
7756 void visitARCStrong(QualType FT, SourceLocation SL) {
7757 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7758 }
7759 void visitARCWeak(QualType FT, SourceLocation SL) {
7760 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7761 }
7762 void visitStruct(QualType FT, SourceLocation SL) {
7763 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7764 visit(FD->getType(), FD->getLocation());
7765 }
7766 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7767 const ArrayType *AT, SourceLocation SL) {
7768 visit(getContext().getBaseElementType(AT), SL);
7769 }
7770 void visitTrivial(QualType FT, SourceLocation SL) {}
7771
7772 static void diag(QualType RT, const Expr *E, Sema &S) {
7773 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7774 }
7775
7776 ASTContext &getContext() { return S.getASTContext(); }
7777
7778 const Expr *E;
7779 Sema &S;
7780};
7781
7782struct SearchNonTrivialToCopyField
7783 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7784 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7785
7786 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7787
7788 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7789 SourceLocation SL) {
7790 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7791 asDerived().visitArray(PCK, AT, SL);
7792 return;
7793 }
7794
7795 Super::visitWithKind(PCK, FT, SL);
7796 }
7797
7798 void visitARCStrong(QualType FT, SourceLocation SL) {
7799 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7800 }
7801 void visitARCWeak(QualType FT, SourceLocation SL) {
7802 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7803 }
7804 void visitStruct(QualType FT, SourceLocation SL) {
7805 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7806 visit(FD->getType(), FD->getLocation());
7807 }
7808 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7809 SourceLocation SL) {
7810 visit(getContext().getBaseElementType(AT), SL);
7811 }
7812 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7813 SourceLocation SL) {}
7814 void visitTrivial(QualType FT, SourceLocation SL) {}
7815 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7816
7817 static void diag(QualType RT, const Expr *E, Sema &S) {
7818 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7819 }
7820
7821 ASTContext &getContext() { return S.getASTContext(); }
7822
7823 const Expr *E;
7824 Sema &S;
7825};
7826
7827}
7828
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007829/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007830///
Chandler Carruthac687262011-06-03 06:23:57 +00007831/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007832/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7833/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007834///
7835/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007836void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007837 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007838 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007839 assert(BId != 0);
7840
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007841 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007842 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007843 unsigned ExpectedNumArgs =
7844 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007845 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007846 return;
7847
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007848 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007849 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007850 unsigned LenArg =
7851 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007852 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007853
Nico Weber0e6daef2013-12-26 23:38:39 +00007854 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7855 Call->getLocStart(), Call->getRParenLoc()))
7856 return;
7857
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007858 // We have special checking when the length is a sizeof expression.
7859 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7860 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7861 llvm::FoldingSetNodeID SizeOfArgID;
7862
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007863 // Although widely used, 'bzero' is not a standard function. Be more strict
7864 // with the argument types before allowing diagnostics and only allow the
7865 // form bzero(ptr, sizeof(...)).
7866 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7867 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7868 return;
7869
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007870 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7871 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007872 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007873
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007874 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007875 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007876 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007877 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007878
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007879 // Never warn about void type pointers. This can be used to suppress
7880 // false positives.
7881 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007882 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007883
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007884 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7885 // actually comparing the expressions for equality. Because computing the
7886 // expression IDs can be expensive, we only do this if the diagnostic is
7887 // enabled.
7888 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007889 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7890 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007891 // We only compute IDs for expressions if the warning is enabled, and
7892 // cache the sizeof arg's ID.
7893 if (SizeOfArgID == llvm::FoldingSetNodeID())
7894 SizeOfArg->Profile(SizeOfArgID, Context, true);
7895 llvm::FoldingSetNodeID DestID;
7896 Dest->Profile(DestID, Context, true);
7897 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007898 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7899 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007900 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007901 StringRef ReadableName = FnName->getName();
7902
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007903 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007904 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007905 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007906 if (!PointeeTy->isIncompleteType() &&
7907 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007908 ActionIdx = 2; // If the pointee's size is sizeof(char),
7909 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007910
7911 // If the function is defined as a builtin macro, do not show macro
7912 // expansion.
7913 SourceLocation SL = SizeOfArg->getExprLoc();
7914 SourceRange DSR = Dest->getSourceRange();
7915 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007916 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007917
7918 if (SM.isMacroArgExpansion(SL)) {
7919 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7920 SL = SM.getSpellingLoc(SL);
7921 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7922 SM.getSpellingLoc(DSR.getEnd()));
7923 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7924 SM.getSpellingLoc(SSR.getEnd()));
7925 }
7926
Anna Zaksd08d9152012-05-30 23:14:52 +00007927 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007928 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007929 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007930 << PointeeTy
7931 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007932 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007933 << SSR);
7934 DiagRuntimeBehavior(SL, SizeOfArg,
7935 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7936 << ActionIdx
7937 << SSR);
7938
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007939 break;
7940 }
7941 }
7942
7943 // Also check for cases where the sizeof argument is the exact same
7944 // type as the memory argument, and where it points to a user-defined
7945 // record type.
7946 if (SizeOfArgTy != QualType()) {
7947 if (PointeeTy->isRecordType() &&
7948 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7949 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7950 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7951 << FnName << SizeOfArgTy << ArgIdx
7952 << PointeeTy << Dest->getSourceRange()
7953 << LenExpr->getSourceRange());
7954 break;
7955 }
Nico Weberc5e73862011-06-14 16:14:58 +00007956 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007957 } else if (DestTy->isArrayType()) {
7958 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007959 }
Nico Weberc5e73862011-06-14 16:14:58 +00007960
Nico Weberc44b35e2015-03-21 17:37:46 +00007961 if (PointeeTy == QualType())
7962 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007963
Nico Weberc44b35e2015-03-21 17:37:46 +00007964 // Always complain about dynamic classes.
7965 bool IsContained;
7966 if (const CXXRecordDecl *ContainedRD =
7967 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007968
Nico Weberc44b35e2015-03-21 17:37:46 +00007969 unsigned OperationType = 0;
7970 // "overwritten" if we're warning about the destination for any call
7971 // but memcmp; otherwise a verb appropriate to the call.
7972 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7973 if (BId == Builtin::BImemcpy)
7974 OperationType = 1;
7975 else if(BId == Builtin::BImemmove)
7976 OperationType = 2;
7977 else if (BId == Builtin::BImemcmp)
7978 OperationType = 3;
7979 }
7980
John McCall31168b02011-06-15 23:02:42 +00007981 DiagRuntimeBehavior(
7982 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007983 PDiag(diag::warn_dyn_class_memaccess)
7984 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7985 << FnName << IsContained << ContainedRD << OperationType
7986 << Call->getCallee()->getSourceRange());
7987 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7988 BId != Builtin::BImemset)
7989 DiagRuntimeBehavior(
7990 Dest->getExprLoc(), Dest,
7991 PDiag(diag::warn_arc_object_memaccess)
7992 << ArgIdx << FnName << PointeeTy
7993 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00007994 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
7995 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
7996 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
7997 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7998 PDiag(diag::warn_cstruct_memaccess)
7999 << ArgIdx << FnName << PointeeTy << 0);
8000 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8001 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8002 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8003 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8004 PDiag(diag::warn_cstruct_memaccess)
8005 << ArgIdx << FnName << PointeeTy << 1);
8006 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8007 } else {
8008 continue;
8009 }
8010 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00008011 continue;
8012
8013 DiagRuntimeBehavior(
8014 Dest->getExprLoc(), Dest,
8015 PDiag(diag::note_bad_memaccess_silence)
8016 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8017 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008018 }
8019}
8020
Ted Kremenek6865f772011-08-18 20:55:45 +00008021// A little helper routine: ignore addition and subtraction of integer literals.
8022// This intentionally does not ignore all integer constant expressions because
8023// we don't want to remove sizeof().
8024static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8025 Ex = Ex->IgnoreParenCasts();
8026
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008027 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00008028 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8029 if (!BO || !BO->isAdditiveOp())
8030 break;
8031
8032 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8033 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8034
8035 if (isa<IntegerLiteral>(RHS))
8036 Ex = LHS;
8037 else if (isa<IntegerLiteral>(LHS))
8038 Ex = RHS;
8039 else
8040 break;
8041 }
8042
8043 return Ex;
8044}
8045
Anna Zaks13b08572012-08-08 21:42:23 +00008046static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8047 ASTContext &Context) {
8048 // Only handle constant-sized or VLAs, but not flexible members.
8049 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8050 // Only issue the FIXIT for arrays of size > 1.
8051 if (CAT->getSize().getSExtValue() <= 1)
8052 return false;
8053 } else if (!Ty->isVariableArrayType()) {
8054 return false;
8055 }
8056 return true;
8057}
8058
Ted Kremenek6865f772011-08-18 20:55:45 +00008059// Warn if the user has made the 'size' argument to strlcpy or strlcat
8060// be the size of the source, instead of the destination.
8061void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8062 IdentifierInfo *FnName) {
8063
8064 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00008065 unsigned NumArgs = Call->getNumArgs();
8066 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00008067 return;
8068
8069 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8070 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00008071 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00008072
8073 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8074 Call->getLocStart(), Call->getRParenLoc()))
8075 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008076
8077 // Look for 'strlcpy(dst, x, sizeof(x))'
8078 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8079 CompareWithSrc = Ex;
8080 else {
8081 // Look for 'strlcpy(dst, x, strlen(x))'
8082 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008083 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8084 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008085 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8086 }
8087 }
8088
8089 if (!CompareWithSrc)
8090 return;
8091
8092 // Determine if the argument to sizeof/strlen is equal to the source
8093 // argument. In principle there's all kinds of things you could do
8094 // here, for instance creating an == expression and evaluating it with
8095 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8096 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8097 if (!SrcArgDRE)
8098 return;
8099
8100 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8101 if (!CompareWithSrcDRE ||
8102 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8103 return;
8104
8105 const Expr *OriginalSizeArg = Call->getArg(2);
8106 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8107 << OriginalSizeArg->getSourceRange() << FnName;
8108
8109 // Output a FIXIT hint if the destination is an array (rather than a
8110 // pointer to an array). This could be enhanced to handle some
8111 // pointers if we know the actual size, like if DstArg is 'array+2'
8112 // we could say 'sizeof(array)-2'.
8113 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008114 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008115 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008116
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008117 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008118 llvm::raw_svector_ostream OS(sizeString);
8119 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008120 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008121 OS << ")";
8122
8123 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8124 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8125 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008126}
8127
Anna Zaks314cd092012-02-01 19:08:57 +00008128/// Check if two expressions refer to the same declaration.
8129static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8130 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8131 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8132 return D1->getDecl() == D2->getDecl();
8133 return false;
8134}
8135
8136static const Expr *getStrlenExprArg(const Expr *E) {
8137 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8138 const FunctionDecl *FD = CE->getDirectCallee();
8139 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008140 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008141 return CE->getArg(0)->IgnoreParenCasts();
8142 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008143 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008144}
8145
8146// Warn on anti-patterns as the 'size' argument to strncat.
8147// The correct size argument should look like following:
8148// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8149void Sema::CheckStrncatArguments(const CallExpr *CE,
8150 IdentifierInfo *FnName) {
8151 // Don't crash if the user has the wrong number of arguments.
8152 if (CE->getNumArgs() < 3)
8153 return;
8154 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8155 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8156 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8157
Nico Weber0e6daef2013-12-26 23:38:39 +00008158 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8159 CE->getRParenLoc()))
8160 return;
8161
Anna Zaks314cd092012-02-01 19:08:57 +00008162 // Identify common expressions, which are wrongly used as the size argument
8163 // to strncat and may lead to buffer overflows.
8164 unsigned PatternType = 0;
8165 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8166 // - sizeof(dst)
8167 if (referToTheSameDecl(SizeOfArg, DstArg))
8168 PatternType = 1;
8169 // - sizeof(src)
8170 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8171 PatternType = 2;
8172 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8173 if (BE->getOpcode() == BO_Sub) {
8174 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8175 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8176 // - sizeof(dst) - strlen(dst)
8177 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8178 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8179 PatternType = 1;
8180 // - sizeof(src) - (anything)
8181 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8182 PatternType = 2;
8183 }
8184 }
8185
8186 if (PatternType == 0)
8187 return;
8188
Anna Zaks5069aa32012-02-03 01:27:37 +00008189 // Generate the diagnostic.
8190 SourceLocation SL = LenArg->getLocStart();
8191 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008192 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008193
8194 // If the function is defined as a builtin macro, do not show macro expansion.
8195 if (SM.isMacroArgExpansion(SL)) {
8196 SL = SM.getSpellingLoc(SL);
8197 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8198 SM.getSpellingLoc(SR.getEnd()));
8199 }
8200
Anna Zaks13b08572012-08-08 21:42:23 +00008201 // Check if the destination is an array (rather than a pointer to an array).
8202 QualType DstTy = DstArg->getType();
8203 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8204 Context);
8205 if (!isKnownSizeArray) {
8206 if (PatternType == 1)
8207 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8208 else
8209 Diag(SL, diag::warn_strncat_src_size) << SR;
8210 return;
8211 }
8212
Anna Zaks314cd092012-02-01 19:08:57 +00008213 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008214 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008215 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008216 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008217
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008218 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008219 llvm::raw_svector_ostream OS(sizeString);
8220 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008221 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008222 OS << ") - ";
8223 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008224 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008225 OS << ") - 1";
8226
Anna Zaks5069aa32012-02-03 01:27:37 +00008227 Diag(SL, diag::note_strncat_wrong_size)
8228 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008229}
8230
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008231//===--- CHECK: Return Address of Stack Variable --------------------------===//
8232
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008233static const Expr *EvalVal(const Expr *E,
8234 SmallVectorImpl<const DeclRefExpr *> &refVars,
8235 const Decl *ParentDecl);
8236static const Expr *EvalAddr(const Expr *E,
8237 SmallVectorImpl<const DeclRefExpr *> &refVars,
8238 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008239
8240/// CheckReturnStackAddr - Check if a return statement returns the address
8241/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008242static void
8243CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8244 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008245 const Expr *stackE = nullptr;
8246 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008247
8248 // Perform checking for returned stack addresses, local blocks,
8249 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008250 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008251 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008252 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008253 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008254 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008255 }
8256
Craig Topperc3ec1492014-05-26 06:22:03 +00008257 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008258 return; // Nothing suspicious was found.
8259
Simon Pilgrim750bde62017-03-31 11:00:53 +00008260 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008261 // of a parameter reference doesn't need a warning.
8262 for (auto *DRE : refVars)
8263 if (isa<ParmVarDecl>(DRE->getDecl()))
8264 return;
8265
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008266 SourceLocation diagLoc;
8267 SourceRange diagRange;
8268 if (refVars.empty()) {
8269 diagLoc = stackE->getLocStart();
8270 diagRange = stackE->getSourceRange();
8271 } else {
8272 // We followed through a reference variable. 'stackE' contains the
8273 // problematic expression but we will warn at the return statement pointing
8274 // at the reference variable. We will later display the "trail" of
8275 // reference variables using notes.
8276 diagLoc = refVars[0]->getLocStart();
8277 diagRange = refVars[0]->getSourceRange();
8278 }
8279
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008280 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8281 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008282 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008283 << DR->getDecl()->getDeclName() << diagRange;
8284 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008285 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008286 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008287 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008288 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008289 // If there is an LValue->RValue conversion, then the value of the
8290 // reference type is used, not the reference.
8291 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8292 if (ICE->getCastKind() == CK_LValueToRValue) {
8293 return;
8294 }
8295 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008296 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8297 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008298 }
8299
8300 // Display the "trail" of reference variables that we followed until we
8301 // found the problematic expression using notes.
8302 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008303 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008304 // If this var binds to another reference var, show the range of the next
8305 // var, otherwise the var binds to the problematic expression, in which case
8306 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008307 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8308 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008309 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8310 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008311 }
8312}
8313
8314/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8315/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008316/// to a location on the stack, a local block, an address of a label, or a
8317/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008318/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008319/// encounter a subexpression that (1) clearly does not lead to one of the
8320/// above problematic expressions (2) is something we cannot determine leads to
8321/// a problematic expression based on such local checking.
8322///
8323/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8324/// the expression that they point to. Such variables are added to the
8325/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008326///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008327/// EvalAddr processes expressions that are pointers that are used as
8328/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008329/// At the base case of the recursion is a check for the above problematic
8330/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008331///
8332/// This implementation handles:
8333///
8334/// * pointer-to-pointer casts
8335/// * implicit conversions from array references to pointers
8336/// * taking the address of fields
8337/// * arbitrary interplay between "&" and "*" operators
8338/// * pointer arithmetic from an address of a stack variable
8339/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008340static const Expr *EvalAddr(const Expr *E,
8341 SmallVectorImpl<const DeclRefExpr *> &refVars,
8342 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008343 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008344 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008345
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008346 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008347 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008348 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008349 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008350 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008351
Peter Collingbourne91147592011-04-15 00:35:48 +00008352 E = E->IgnoreParens();
8353
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008354 // Our "symbolic interpreter" is just a dispatch off the currently
8355 // viewed AST node. We then recursively traverse the AST by calling
8356 // EvalAddr and EvalVal appropriately.
8357 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008358 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008359 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008360
Richard Smith40f08eb2014-01-30 22:05:38 +00008361 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008362 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008363 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008364
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008365 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008366 // If this is a reference variable, follow through to the expression that
8367 // it points to.
8368 if (V->hasLocalStorage() &&
8369 V->getType()->isReferenceType() && V->hasInit()) {
8370 // Add the reference variable to the "trail".
8371 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008372 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008373 }
8374
Craig Topperc3ec1492014-05-26 06:22:03 +00008375 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008376 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008377
Chris Lattner934edb22007-12-28 05:31:15 +00008378 case Stmt::UnaryOperatorClass: {
8379 // The only unary operator that make sense to handle here
8380 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008381 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008382
John McCalle3027922010-08-25 11:45:40 +00008383 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008384 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008385 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008386 }
Mike Stump11289f42009-09-09 15:08:12 +00008387
Chris Lattner934edb22007-12-28 05:31:15 +00008388 case Stmt::BinaryOperatorClass: {
8389 // Handle pointer arithmetic. All other binary operators are not valid
8390 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008391 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008392 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008393
John McCalle3027922010-08-25 11:45:40 +00008394 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008395 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008396
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008397 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008398
8399 // Determine which argument is the real pointer base. It could be
8400 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008401 if (!Base->getType()->isPointerType())
8402 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008403
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008404 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008405 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008406 }
Steve Naroff2752a172008-09-10 19:17:48 +00008407
Chris Lattner934edb22007-12-28 05:31:15 +00008408 // For conditional operators we need to see if either the LHS or RHS are
8409 // valid DeclRefExpr*s. If one of them is valid, we return it.
8410 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008411 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008412
Chris Lattner934edb22007-12-28 05:31:15 +00008413 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008414 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008415 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008416 // In C++, we can have a throw-expression, which has 'void' type.
8417 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008418 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008419 return LHS;
8420 }
Chris Lattner934edb22007-12-28 05:31:15 +00008421
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008422 // In C++, we can have a throw-expression, which has 'void' type.
8423 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008424 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008425
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008426 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008427 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008428
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008429 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008430 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008431 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008432 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008433
8434 case Stmt::AddrLabelExprClass:
8435 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008436
John McCall28fc7092011-11-10 05:35:25 +00008437 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008438 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8439 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008440
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008441 // For casts, we need to handle conversions from arrays to
8442 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008443 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008444 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008445 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008446 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008447 case Stmt::CXXStaticCastExprClass:
8448 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008449 case Stmt::CXXConstCastExprClass:
8450 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008451 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008452 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008453 case CK_LValueToRValue:
8454 case CK_NoOp:
8455 case CK_BaseToDerived:
8456 case CK_DerivedToBase:
8457 case CK_UncheckedDerivedToBase:
8458 case CK_Dynamic:
8459 case CK_CPointerToObjCPointerCast:
8460 case CK_BlockPointerToObjCPointerCast:
8461 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008462 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008463
8464 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008465 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008466
Richard Trieudadefde2014-07-02 04:39:38 +00008467 case CK_BitCast:
8468 if (SubExpr->getType()->isAnyPointerType() ||
8469 SubExpr->getType()->isBlockPointerType() ||
8470 SubExpr->getType()->isObjCQualifiedIdType())
8471 return EvalAddr(SubExpr, refVars, ParentDecl);
8472 else
8473 return nullptr;
8474
Eli Friedman8195ad72012-02-23 23:04:32 +00008475 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008476 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008477 }
Chris Lattner934edb22007-12-28 05:31:15 +00008478 }
Mike Stump11289f42009-09-09 15:08:12 +00008479
Douglas Gregorfe314812011-06-21 17:03:29 +00008480 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008481 if (const Expr *Result =
8482 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8483 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008484 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008485 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008486
Chris Lattner934edb22007-12-28 05:31:15 +00008487 // Everything else: we simply don't reason about them.
8488 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008489 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008490 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008491}
Mike Stump11289f42009-09-09 15:08:12 +00008492
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008493/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8494/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008495static const Expr *EvalVal(const Expr *E,
8496 SmallVectorImpl<const DeclRefExpr *> &refVars,
8497 const Decl *ParentDecl) {
8498 do {
8499 // We should only be called for evaluating non-pointer expressions, or
8500 // expressions with a pointer type that are not used as references but
8501 // instead
8502 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008503
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008504 // Our "symbolic interpreter" is just a dispatch off the currently
8505 // viewed AST node. We then recursively traverse the AST by calling
8506 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008507
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008508 E = E->IgnoreParens();
8509 switch (E->getStmtClass()) {
8510 case Stmt::ImplicitCastExprClass: {
8511 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8512 if (IE->getValueKind() == VK_LValue) {
8513 E = IE->getSubExpr();
8514 continue;
8515 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008516 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008517 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008518
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008519 case Stmt::ExprWithCleanupsClass:
8520 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8521 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008522
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008523 case Stmt::DeclRefExprClass: {
8524 // When we hit a DeclRefExpr we are looking at code that refers to a
8525 // variable's name. If it's not a reference variable we check if it has
8526 // local storage within the function, and if so, return the expression.
8527 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8528
8529 // If we leave the immediate function, the lifetime isn't about to end.
8530 if (DR->refersToEnclosingVariableOrCapture())
8531 return nullptr;
8532
8533 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8534 // Check if it refers to itself, e.g. "int& i = i;".
8535 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008536 return DR;
8537
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008538 if (V->hasLocalStorage()) {
8539 if (!V->getType()->isReferenceType())
8540 return DR;
8541
8542 // Reference variable, follow through to the expression that
8543 // it points to.
8544 if (V->hasInit()) {
8545 // Add the reference variable to the "trail".
8546 refVars.push_back(DR);
8547 return EvalVal(V->getInit(), refVars, V);
8548 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008549 }
8550 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008551
8552 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008553 }
Mike Stump11289f42009-09-09 15:08:12 +00008554
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008555 case Stmt::UnaryOperatorClass: {
8556 // The only unary operator that make sense to handle here
8557 // is Deref. All others don't resolve to a "name." This includes
8558 // handling all sorts of rvalues passed to a unary operator.
8559 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008560
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008561 if (U->getOpcode() == UO_Deref)
8562 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008563
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008564 return nullptr;
8565 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008566
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008567 case Stmt::ArraySubscriptExprClass: {
8568 // Array subscripts are potential references to data on the stack. We
8569 // retrieve the DeclRefExpr* for the array variable if it indeed
8570 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008571 const auto *ASE = cast<ArraySubscriptExpr>(E);
8572 if (ASE->isTypeDependent())
8573 return nullptr;
8574 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008575 }
Mike Stump11289f42009-09-09 15:08:12 +00008576
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008577 case Stmt::OMPArraySectionExprClass: {
8578 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8579 ParentDecl);
8580 }
Mike Stump11289f42009-09-09 15:08:12 +00008581
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008582 case Stmt::ConditionalOperatorClass: {
8583 // For conditional operators we need to see if either the LHS or RHS are
8584 // non-NULL Expr's. If one is non-NULL, we return it.
8585 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008586
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008587 // Handle the GNU extension for missing LHS.
8588 if (const Expr *LHSExpr = C->getLHS()) {
8589 // In C++, we can have a throw-expression, which has 'void' type.
8590 if (!LHSExpr->getType()->isVoidType())
8591 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8592 return LHS;
8593 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008594
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008595 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008596 if (C->getRHS()->getType()->isVoidType())
8597 return nullptr;
8598
8599 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008600 }
8601
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008602 // Accesses to members are potential references to data on the stack.
8603 case Stmt::MemberExprClass: {
8604 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008605
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008606 // Check for indirect access. We only want direct field accesses.
8607 if (M->isArrow())
8608 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008609
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008610 // Check whether the member type is itself a reference, in which case
8611 // we're not going to refer to the member, but to what the member refers
8612 // to.
8613 if (M->getMemberDecl()->getType()->isReferenceType())
8614 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008615
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008616 return EvalVal(M->getBase(), refVars, ParentDecl);
8617 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008618
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008619 case Stmt::MaterializeTemporaryExprClass:
8620 if (const Expr *Result =
8621 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8622 refVars, ParentDecl))
8623 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008624 return E;
8625
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008626 default:
8627 // Check that we don't return or take the address of a reference to a
8628 // temporary. This is only useful in C++.
8629 if (!E->isTypeDependent() && E->isRValue())
8630 return E;
8631
8632 // Everything else: we simply don't reason about them.
8633 return nullptr;
8634 }
8635 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008636}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008637
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008638void
8639Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8640 SourceLocation ReturnLoc,
8641 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008642 const AttrVec *Attrs,
8643 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008644 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8645
8646 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008647 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8648 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008649 CheckNonNullExpr(*this, RetValExp))
8650 Diag(ReturnLoc, diag::warn_null_ret)
8651 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008652
8653 // C++11 [basic.stc.dynamic.allocation]p4:
8654 // If an allocation function declared with a non-throwing
8655 // exception-specification fails to allocate storage, it shall return
8656 // a null pointer. Any other allocation function that fails to allocate
8657 // storage shall indicate failure only by throwing an exception [...]
8658 if (FD) {
8659 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8660 if (Op == OO_New || Op == OO_Array_New) {
8661 const FunctionProtoType *Proto
8662 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008663 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008664 CheckNonNullExpr(*this, RetValExp))
8665 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8666 << FD << getLangOpts().CPlusPlus11;
8667 }
8668 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008669}
8670
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008671//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8672
8673/// Check for comparisons of floating point operands using != and ==.
8674/// Issue a warning if these are no self-comparisons, as they are not likely
8675/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008676void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008677 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8678 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008679
8680 // Special case: check for x == x (which is OK).
8681 // Do not emit warnings for such cases.
8682 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8683 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8684 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008685 return;
Mike Stump11289f42009-09-09 15:08:12 +00008686
Ted Kremenekeda40e22007-11-29 00:59:04 +00008687 // Special case: check for comparisons against literals that can be exactly
8688 // represented by APFloat. In such cases, do not emit a warning. This
8689 // is a heuristic: often comparison against such literals are used to
8690 // detect if a value in a variable has not changed. This clearly can
8691 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008692 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8693 if (FLL->isExact())
8694 return;
8695 } else
8696 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8697 if (FLR->isExact())
8698 return;
Mike Stump11289f42009-09-09 15:08:12 +00008699
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008700 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008701 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008702 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008703 return;
Mike Stump11289f42009-09-09 15:08:12 +00008704
David Blaikie1f4ff152012-07-16 20:47:22 +00008705 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008706 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008707 return;
Mike Stump11289f42009-09-09 15:08:12 +00008708
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008709 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008710 Diag(Loc, diag::warn_floatingpoint_eq)
8711 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008712}
John McCallca01b222010-01-04 23:21:16 +00008713
John McCall70aa5392010-01-06 05:24:50 +00008714//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8715//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008716
John McCall70aa5392010-01-06 05:24:50 +00008717namespace {
John McCallca01b222010-01-04 23:21:16 +00008718
John McCall70aa5392010-01-06 05:24:50 +00008719/// Structure recording the 'active' range of an integer-valued
8720/// expression.
8721struct IntRange {
8722 /// The number of bits active in the int.
8723 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008724
John McCall70aa5392010-01-06 05:24:50 +00008725 /// True if the int is known not to have negative values.
8726 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008727
John McCall70aa5392010-01-06 05:24:50 +00008728 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008729 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008730
John McCall817d4af2010-11-10 23:38:19 +00008731 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008732 static IntRange forBoolType() {
8733 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008734 }
8735
John McCall817d4af2010-11-10 23:38:19 +00008736 /// Returns the range of an opaque value of the given integral type.
8737 static IntRange forValueOfType(ASTContext &C, QualType T) {
8738 return forValueOfCanonicalType(C,
8739 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008740 }
8741
John McCall817d4af2010-11-10 23:38:19 +00008742 /// Returns the range of an opaque value of a canonical integral type.
8743 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008744 assert(T->isCanonicalUnqualified());
8745
8746 if (const VectorType *VT = dyn_cast<VectorType>(T))
8747 T = VT->getElementType().getTypePtr();
8748 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8749 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008750 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8751 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008752
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008753 if (!C.getLangOpts().CPlusPlus) {
8754 // For enum types in C code, use the underlying datatype.
8755 if (const EnumType *ET = dyn_cast<EnumType>(T))
8756 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8757 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8758 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008759 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008760 // In C++11, enums can have a fixed underlying type. Use this type to
8761 // compute the range.
8762 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008763 return IntRange(C.getIntWidth(QualType(T, 0)),
8764 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008765 }
John McCall18a2c2c2010-11-09 22:22:12 +00008766
David Majnemer6a426652013-06-07 22:07:20 +00008767 unsigned NumPositive = Enum->getNumPositiveBits();
8768 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008769
David Majnemer6a426652013-06-07 22:07:20 +00008770 if (NumNegative == 0)
8771 return IntRange(NumPositive, true/*NonNegative*/);
8772 else
8773 return IntRange(std::max(NumPositive + 1, NumNegative),
8774 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008775 }
John McCall70aa5392010-01-06 05:24:50 +00008776
8777 const BuiltinType *BT = cast<BuiltinType>(T);
8778 assert(BT->isInteger());
8779
8780 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8781 }
8782
John McCall817d4af2010-11-10 23:38:19 +00008783 /// Returns the "target" range of a canonical integral type, i.e.
8784 /// the range of values expressible in the type.
8785 ///
8786 /// This matches forValueOfCanonicalType except that enums have the
8787 /// full range of their type, not the range of their enumerators.
8788 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8789 assert(T->isCanonicalUnqualified());
8790
8791 if (const VectorType *VT = dyn_cast<VectorType>(T))
8792 T = VT->getElementType().getTypePtr();
8793 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8794 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008795 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8796 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008797 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008798 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008799
8800 const BuiltinType *BT = cast<BuiltinType>(T);
8801 assert(BT->isInteger());
8802
8803 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8804 }
8805
8806 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008807 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008808 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008809 L.NonNegative && R.NonNegative);
8810 }
8811
John McCall817d4af2010-11-10 23:38:19 +00008812 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008813 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008814 return IntRange(std::min(L.Width, R.Width),
8815 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008816 }
8817};
8818
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008819} // namespace
8820
8821static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8822 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008823 if (value.isSigned() && value.isNegative())
8824 return IntRange(value.getMinSignedBits(), false);
8825
8826 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008827 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008828
8829 // isNonNegative() just checks the sign bit without considering
8830 // signedness.
8831 return IntRange(value.getActiveBits(), true);
8832}
8833
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008834static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8835 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008836 if (result.isInt())
8837 return GetValueRange(C, result.getInt(), MaxWidth);
8838
8839 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008840 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8841 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8842 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8843 R = IntRange::join(R, El);
8844 }
John McCall70aa5392010-01-06 05:24:50 +00008845 return R;
8846 }
8847
8848 if (result.isComplexInt()) {
8849 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8850 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8851 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008852 }
8853
8854 // This can happen with lossless casts to intptr_t of "based" lvalues.
8855 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008856 // FIXME: The only reason we need to pass the type in here is to get
8857 // the sign right on this one case. It would be nice if APValue
8858 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008859 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008860 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008861}
John McCall70aa5392010-01-06 05:24:50 +00008862
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008863static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008864 QualType Ty = E->getType();
8865 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8866 Ty = AtomicRHS->getValueType();
8867 return Ty;
8868}
8869
John McCall70aa5392010-01-06 05:24:50 +00008870/// Pseudo-evaluate the given integer expression, estimating the
8871/// range of values it might take.
8872///
8873/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008874static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008875 E = E->IgnoreParens();
8876
8877 // Try a full evaluation first.
8878 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008879 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008880 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008881
8882 // I think we only want to look through implicit casts here; if the
8883 // user has an explicit widening cast, we should treat the value as
8884 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008885 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008886 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008887 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8888
Eli Friedmane6d33952013-07-08 20:20:06 +00008889 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008890
George Burgess IVdf1ed002016-01-13 01:52:39 +00008891 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8892 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008893
John McCall70aa5392010-01-06 05:24:50 +00008894 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008895 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008896 return OutputTypeRange;
8897
8898 IntRange SubRange
8899 = GetExprRange(C, CE->getSubExpr(),
8900 std::min(MaxWidth, OutputTypeRange.Width));
8901
8902 // Bail out if the subexpr's range is as wide as the cast type.
8903 if (SubRange.Width >= OutputTypeRange.Width)
8904 return OutputTypeRange;
8905
8906 // Otherwise, we take the smaller width, and we're non-negative if
8907 // either the output type or the subexpr is.
8908 return IntRange(SubRange.Width,
8909 SubRange.NonNegative || OutputTypeRange.NonNegative);
8910 }
8911
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008912 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008913 // If we can fold the condition, just take that operand.
8914 bool CondResult;
8915 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8916 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8917 : CO->getFalseExpr(),
8918 MaxWidth);
8919
8920 // Otherwise, conservatively merge.
8921 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8922 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8923 return IntRange::join(L, R);
8924 }
8925
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008926 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008927 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008928 case BO_Cmp:
8929 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008930
8931 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008932 case BO_LAnd:
8933 case BO_LOr:
8934 case BO_LT:
8935 case BO_GT:
8936 case BO_LE:
8937 case BO_GE:
8938 case BO_EQ:
8939 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008940 return IntRange::forBoolType();
8941
John McCallc3688382011-07-13 06:35:24 +00008942 // The type of the assignments is the type of the LHS, so the RHS
8943 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008944 case BO_MulAssign:
8945 case BO_DivAssign:
8946 case BO_RemAssign:
8947 case BO_AddAssign:
8948 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008949 case BO_XorAssign:
8950 case BO_OrAssign:
8951 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008952 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008953
John McCallc3688382011-07-13 06:35:24 +00008954 // Simple assignments just pass through the RHS, which will have
8955 // been coerced to the LHS type.
8956 case BO_Assign:
8957 // TODO: bitfields?
8958 return GetExprRange(C, BO->getRHS(), MaxWidth);
8959
John McCall70aa5392010-01-06 05:24:50 +00008960 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008961 case BO_PtrMemD:
8962 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008963 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008964
John McCall2ce81ad2010-01-06 22:07:33 +00008965 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008966 case BO_And:
8967 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008968 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8969 GetExprRange(C, BO->getRHS(), MaxWidth));
8970
John McCall70aa5392010-01-06 05:24:50 +00008971 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008972 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008973 // ...except that we want to treat '1 << (blah)' as logically
8974 // positive. It's an important idiom.
8975 if (IntegerLiteral *I
8976 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8977 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008978 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008979 return IntRange(R.Width, /*NonNegative*/ true);
8980 }
8981 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008982 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008983
John McCalle3027922010-08-25 11:45:40 +00008984 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008985 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008986
John McCall2ce81ad2010-01-06 22:07:33 +00008987 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008988 case BO_Shr:
8989 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008990 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8991
8992 // If the shift amount is a positive constant, drop the width by
8993 // that much.
8994 llvm::APSInt shift;
8995 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8996 shift.isNonNegative()) {
8997 unsigned zext = shift.getZExtValue();
8998 if (zext >= L.Width)
8999 L.Width = (L.NonNegative ? 0 : 1);
9000 else
9001 L.Width -= zext;
9002 }
9003
9004 return L;
9005 }
9006
9007 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009008 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009009 return GetExprRange(C, BO->getRHS(), MaxWidth);
9010
John McCall2ce81ad2010-01-06 22:07:33 +00009011 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009012 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009013 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009014 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009015 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009016
John McCall51431812011-07-14 22:39:48 +00009017 // The width of a division result is mostly determined by the size
9018 // of the LHS.
9019 case BO_Div: {
9020 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009021 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009022 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9023
9024 // If the divisor is constant, use that.
9025 llvm::APSInt divisor;
9026 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9027 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9028 if (log2 >= L.Width)
9029 L.Width = (L.NonNegative ? 0 : 1);
9030 else
9031 L.Width = std::min(L.Width - log2, MaxWidth);
9032 return L;
9033 }
9034
9035 // Otherwise, just use the LHS's width.
9036 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9037 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9038 }
9039
9040 // The result of a remainder can't be larger than the result of
9041 // either side.
9042 case BO_Rem: {
9043 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009044 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009045 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9046 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9047
9048 IntRange meet = IntRange::meet(L, R);
9049 meet.Width = std::min(meet.Width, MaxWidth);
9050 return meet;
9051 }
9052
9053 // The default behavior is okay for these.
9054 case BO_Mul:
9055 case BO_Add:
9056 case BO_Xor:
9057 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009058 break;
9059 }
9060
John McCall51431812011-07-14 22:39:48 +00009061 // The default case is to treat the operation as if it were closed
9062 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009063 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9064 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9065 return IntRange::join(L, R);
9066 }
9067
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009068 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009069 switch (UO->getOpcode()) {
9070 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009071 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009072 return IntRange::forBoolType();
9073
9074 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009075 case UO_Deref:
9076 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009077 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009078
9079 default:
9080 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9081 }
9082 }
9083
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009084 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009085 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9086
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009087 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009088 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009089 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009090
Eli Friedmane6d33952013-07-08 20:20:06 +00009091 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009092}
John McCall263a48b2010-01-04 23:31:57 +00009093
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009094static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009095 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009096}
9097
John McCall263a48b2010-01-04 23:31:57 +00009098/// Checks whether the given value, which currently has the given
9099/// source semantics, has the same value when coerced through the
9100/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009101static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9102 const llvm::fltSemantics &Src,
9103 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009104 llvm::APFloat truncated = value;
9105
9106 bool ignored;
9107 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9108 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9109
9110 return truncated.bitwiseIsEqual(value);
9111}
9112
9113/// Checks whether the given value, which currently has the given
9114/// source semantics, has the same value when coerced through the
9115/// target semantics.
9116///
9117/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009118static bool IsSameFloatAfterCast(const APValue &value,
9119 const llvm::fltSemantics &Src,
9120 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009121 if (value.isFloat())
9122 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9123
9124 if (value.isVector()) {
9125 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9126 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9127 return false;
9128 return true;
9129 }
9130
9131 assert(value.isComplexFloat());
9132 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9133 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9134}
9135
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009136static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009137
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009138static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009139 // Suppress cases where we are comparing against an enum constant.
9140 if (const DeclRefExpr *DR =
9141 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9142 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009143 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009144
9145 // Suppress cases where the '0' value is expanded from a macro.
9146 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009147 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009148
Roman Lebedev6de129e2017-10-15 20:13:17 +00009149 return false;
9150}
9151
Richard Smith692f66ab2017-12-06 19:23:19 +00009152static bool isKnownToHaveUnsignedValue(Expr *E) {
9153 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009154 (!E->getType()->isSignedIntegerType() ||
9155 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9156}
9157
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009158namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009159/// The promoted range of values of a type. In general this has the
9160/// following structure:
9161///
9162/// |-----------| . . . |-----------|
9163/// ^ ^ ^ ^
9164/// Min HoleMin HoleMax Max
9165///
9166/// ... where there is only a hole if a signed type is promoted to unsigned
9167/// (in which case Min and Max are the smallest and largest representable
9168/// values).
9169struct PromotedRange {
9170 // Min, or HoleMax if there is a hole.
9171 llvm::APSInt PromotedMin;
9172 // Max, or HoleMin if there is a hole.
9173 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009174
Richard Smitha5370fb2017-12-08 22:57:11 +00009175 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9176 if (R.Width == 0)
9177 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9178 else if (R.Width >= BitWidth && !Unsigned) {
9179 // Promotion made the type *narrower*. This happens when promoting
9180 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9181 // Treat all values of 'signed int' as being in range for now.
9182 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9183 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9184 } else {
9185 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9186 .extOrTrunc(BitWidth);
9187 PromotedMin.setIsUnsigned(Unsigned);
9188
9189 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9190 .extOrTrunc(BitWidth);
9191 PromotedMax.setIsUnsigned(Unsigned);
9192 }
9193 }
9194
9195 // Determine whether this range is contiguous (has no hole).
9196 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9197
9198 // Where a constant value is within the range.
9199 enum ComparisonResult {
9200 LT = 0x1,
9201 LE = 0x2,
9202 GT = 0x4,
9203 GE = 0x8,
9204 EQ = 0x10,
9205 NE = 0x20,
9206 InRangeFlag = 0x40,
9207
9208 Less = LE | LT | NE,
9209 Min = LE | InRangeFlag,
9210 InRange = InRangeFlag,
9211 Max = GE | InRangeFlag,
9212 Greater = GE | GT | NE,
9213
9214 OnlyValue = LE | GE | EQ | InRangeFlag,
9215 InHole = NE
9216 };
9217
9218 ComparisonResult compare(const llvm::APSInt &Value) const {
9219 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9220 Value.isUnsigned() == PromotedMin.isUnsigned());
9221 if (!isContiguous()) {
9222 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9223 if (Value.isMinValue()) return Min;
9224 if (Value.isMaxValue()) return Max;
9225 if (Value >= PromotedMin) return InRange;
9226 if (Value <= PromotedMax) return InRange;
9227 return InHole;
9228 }
9229
9230 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9231 case -1: return Less;
9232 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9233 case 1:
9234 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9235 case -1: return InRange;
9236 case 0: return Max;
9237 case 1: return Greater;
9238 }
9239 }
9240
9241 llvm_unreachable("impossible compare result");
9242 }
9243
Richard Smithc70f1d62017-12-14 15:16:18 +00009244 static llvm::Optional<StringRef>
9245 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9246 if (Op == BO_Cmp) {
9247 ComparisonResult LTFlag = LT, GTFlag = GT;
9248 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9249
9250 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9251 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9252 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9253 return llvm::None;
9254 }
9255
Richard Smitha5370fb2017-12-08 22:57:11 +00009256 ComparisonResult TrueFlag, FalseFlag;
9257 if (Op == BO_EQ) {
9258 TrueFlag = EQ;
9259 FalseFlag = NE;
9260 } else if (Op == BO_NE) {
9261 TrueFlag = NE;
9262 FalseFlag = EQ;
9263 } else {
9264 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9265 TrueFlag = LT;
9266 FalseFlag = GE;
9267 } else {
9268 TrueFlag = GT;
9269 FalseFlag = LE;
9270 }
9271 if (Op == BO_GE || Op == BO_LE)
9272 std::swap(TrueFlag, FalseFlag);
9273 }
9274 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009275 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009276 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009277 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009278 return llvm::None;
9279 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009280};
John McCallcc7e5bf2010-05-06 08:58:33 +00009281}
9282
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009283static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009284 // Strip off implicit integral promotions.
9285 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009286 if (ICE->getCastKind() != CK_IntegralCast &&
9287 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009288 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009289 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009290 }
9291
9292 return E->getType()->isEnumeralType();
9293}
9294
Richard Smith692f66ab2017-12-06 19:23:19 +00009295static int classifyConstantValue(Expr *Constant) {
9296 // The values of this enumeration are used in the diagnostics
9297 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9298 enum ConstantValueKind {
9299 Miscellaneous = 0,
9300 LiteralTrue,
9301 LiteralFalse
9302 };
9303 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9304 return BL->getValue() ? ConstantValueKind::LiteralTrue
9305 : ConstantValueKind::LiteralFalse;
9306 return ConstantValueKind::Miscellaneous;
9307}
9308
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009309static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9310 Expr *Constant, Expr *Other,
9311 const llvm::APSInt &Value,
9312 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009313 if (S.inTemplateInstantiation())
9314 return false;
9315
Richard Smitha5370fb2017-12-08 22:57:11 +00009316 Expr *OriginalOther = Other;
9317
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009318 Constant = Constant->IgnoreParenImpCasts();
9319 Other = Other->IgnoreParenImpCasts();
9320
Richard Smitha5370fb2017-12-08 22:57:11 +00009321 // Suppress warnings on tautological comparisons between values of the same
9322 // enumeration type. There are only two ways we could warn on this:
9323 // - If the constant is outside the range of representable values of
9324 // the enumeration. In such a case, we should warn about the cast
9325 // to enumeration type, not about the comparison.
9326 // - If the constant is the maximum / minimum in-range value. For an
9327 // enumeratin type, such comparisons can be meaningful and useful.
9328 if (Constant->getType()->isEnumeralType() &&
9329 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9330 return false;
9331
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009332 // TODO: Investigate using GetExprRange() to get tighter bounds
9333 // on the bit ranges.
9334 QualType OtherT = Other->getType();
9335 if (const auto *AT = OtherT->getAs<AtomicType>())
9336 OtherT = AT->getValueType();
9337 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9338
9339 // Whether we're treating Other as being a bool because of the form of
9340 // expression despite it having another type (typically 'int' in C).
9341 bool OtherIsBooleanDespiteType =
9342 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9343 if (OtherIsBooleanDespiteType)
9344 OtherRange = IntRange::forBoolType();
9345
Richard Smitha5370fb2017-12-08 22:57:11 +00009346 // Determine the promoted range of the other type and see if a comparison of
9347 // the constant against that range is tautological.
9348 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9349 Value.isUnsigned());
9350 auto Cmp = OtherPromotedRange.compare(Value);
9351 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9352 if (!Result)
9353 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009354
Richard Smitha5370fb2017-12-08 22:57:11 +00009355 // Suppress the diagnostic for an in-range comparison if the constant comes
9356 // from a macro or enumerator. We don't want to diagnose
9357 //
9358 // some_long_value <= INT_MAX
9359 //
9360 // when sizeof(int) == sizeof(long).
9361 bool InRange = Cmp & PromotedRange::InRangeFlag;
9362 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9363 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009364
9365 // If this is a comparison to an enum constant, include that
9366 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009367 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009368 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9369 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9370
Richard Smitha5370fb2017-12-08 22:57:11 +00009371 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009372 SmallString<64> PrettySourceValue;
9373 llvm::raw_svector_ostream OS(PrettySourceValue);
9374 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009375 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009376 else
9377 OS << Value;
9378
Richard Smitha5370fb2017-12-08 22:57:11 +00009379 // FIXME: We use a somewhat different formatting for the in-range cases and
9380 // cases involving boolean values for historical reasons. We should pick a
9381 // consistent way of presenting these diagnostics.
9382 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9383 S.DiagRuntimeBehavior(
9384 E->getOperatorLoc(), E,
9385 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9386 : diag::warn_tautological_bool_compare)
9387 << OS.str() << classifyConstantValue(Constant)
9388 << OtherT << OtherIsBooleanDespiteType << *Result
9389 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9390 } else {
9391 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9392 ? (HasEnumType(OriginalOther)
9393 ? diag::warn_unsigned_enum_always_true_comparison
9394 : diag::warn_unsigned_always_true_comparison)
9395 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009396
Richard Smitha5370fb2017-12-08 22:57:11 +00009397 S.Diag(E->getOperatorLoc(), Diag)
9398 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9399 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9400 }
9401
9402 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009403}
9404
John McCallcc7e5bf2010-05-06 08:58:33 +00009405/// Analyze the operands of the given comparison. Implements the
9406/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009407static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009408 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9409 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009410}
John McCall263a48b2010-01-04 23:31:57 +00009411
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009412/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009413///
Richard Trieu82402a02011-09-15 21:56:47 +00009414/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009415static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009416 // The type the comparison is being performed in.
9417 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009418
9419 // Only analyze comparison operators where both sides have been converted to
9420 // the same type.
9421 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9422 return AnalyzeImpConvsInComparison(S, E);
9423
9424 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009425 if (E->isValueDependent())
9426 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009427
Roman Lebedev6de129e2017-10-15 20:13:17 +00009428 Expr *LHS = E->getLHS();
9429 Expr *RHS = E->getRHS();
9430
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009431 if (T->isIntegralType(S.Context)) {
9432 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009433 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009434
Roman Lebedev6de129e2017-10-15 20:13:17 +00009435 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9436 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009437
Roman Lebedev6de129e2017-10-15 20:13:17 +00009438 // We don't care about expressions whose result is a constant.
9439 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9440 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009441
Roman Lebedev6de129e2017-10-15 20:13:17 +00009442 // We only care about expressions where just one side is literal
9443 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9444 // Is the constant on the RHS or LHS?
9445 const bool RhsConstant = IsRHSIntegralLiteral;
9446 Expr *Const = RhsConstant ? RHS : LHS;
9447 Expr *Other = RhsConstant ? LHS : RHS;
9448 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9449
9450 // Check whether an integer constant comparison results in a value
9451 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009452 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9453 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009454 }
9455 }
9456
9457 if (!T->hasUnsignedIntegerRepresentation()) {
9458 // We don't do anything special if this isn't an unsigned integral
9459 // comparison: we're only interested in integral comparisons, and
9460 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009461 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009462 }
9463
9464 LHS = LHS->IgnoreParenImpCasts();
9465 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009466
Alex Lorenzb57409f2018-02-07 20:45:39 +00009467 if (!S.getLangOpts().CPlusPlus) {
9468 // Avoid warning about comparison of integers with different signs when
9469 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9470 // the type of `E`.
9471 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9472 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9473 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9474 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9475 }
9476
John McCallcc7e5bf2010-05-06 08:58:33 +00009477 // Check to see if one of the (unmodified) operands is of different
9478 // signedness.
9479 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009480 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9481 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009482 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009483 signedOperand = LHS;
9484 unsignedOperand = RHS;
9485 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9486 signedOperand = RHS;
9487 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009488 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009489 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009490 }
9491
John McCallcc7e5bf2010-05-06 08:58:33 +00009492 // Otherwise, calculate the effective range of the signed operand.
9493 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009494
John McCallcc7e5bf2010-05-06 08:58:33 +00009495 // Go ahead and analyze implicit conversions in the operands. Note
9496 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009497 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9498 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009499
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009500 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009501 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009502 return;
John McCallca01b222010-01-04 23:21:16 +00009503
9504 // For (in)equality comparisons, if the unsigned operand is a
9505 // constant which cannot collide with a overflowed signed operand,
9506 // then reinterpreting the signed operand as unsigned will not
9507 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009508 if (E->isEqualityOp()) {
9509 unsigned comparisonWidth = S.Context.getIntWidth(T);
9510 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009511
John McCallcc7e5bf2010-05-06 08:58:33 +00009512 // We should never be unable to prove that the unsigned operand is
9513 // non-negative.
9514 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9515
9516 if (unsignedRange.Width < comparisonWidth)
9517 return;
9518 }
9519
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009520 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9521 S.PDiag(diag::warn_mixed_sign_comparison)
9522 << LHS->getType() << RHS->getType()
9523 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009524}
9525
John McCall1f425642010-11-11 03:21:53 +00009526/// Analyzes an attempt to assign the given value to a bitfield.
9527///
9528/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009529static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9530 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009531 assert(Bitfield->isBitField());
9532 if (Bitfield->isInvalidDecl())
9533 return false;
9534
John McCalldeebbcf2010-11-11 05:33:51 +00009535 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009536 QualType BitfieldType = Bitfield->getType();
9537 if (BitfieldType->isBooleanType())
9538 return false;
9539
9540 if (BitfieldType->isEnumeralType()) {
9541 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9542 // If the underlying enum type was not explicitly specified as an unsigned
9543 // type and the enum contain only positive values, MSVC++ will cause an
9544 // inconsistency by storing this as a signed type.
9545 if (S.getLangOpts().CPlusPlus11 &&
9546 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9547 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9548 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9549 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9550 << BitfieldEnumDecl->getNameAsString();
9551 }
9552 }
9553
John McCalldeebbcf2010-11-11 05:33:51 +00009554 if (Bitfield->getType()->isBooleanType())
9555 return false;
9556
Douglas Gregor789adec2011-02-04 13:09:01 +00009557 // Ignore value- or type-dependent expressions.
9558 if (Bitfield->getBitWidth()->isValueDependent() ||
9559 Bitfield->getBitWidth()->isTypeDependent() ||
9560 Init->isValueDependent() ||
9561 Init->isTypeDependent())
9562 return false;
9563
John McCall1f425642010-11-11 03:21:53 +00009564 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009565 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009566
Richard Smith5fab0c92011-12-28 19:48:30 +00009567 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009568 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9569 Expr::SE_AllowSideEffects)) {
9570 // The RHS is not constant. If the RHS has an enum type, make sure the
9571 // bitfield is wide enough to hold all the values of the enum without
9572 // truncation.
9573 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9574 EnumDecl *ED = EnumTy->getDecl();
9575 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9576
9577 // Enum types are implicitly signed on Windows, so check if there are any
9578 // negative enumerators to see if the enum was intended to be signed or
9579 // not.
9580 bool SignedEnum = ED->getNumNegativeBits() > 0;
9581
9582 // Check for surprising sign changes when assigning enum values to a
9583 // bitfield of different signedness. If the bitfield is signed and we
9584 // have exactly the right number of bits to store this unsigned enum,
9585 // suggest changing the enum to an unsigned type. This typically happens
9586 // on Windows where unfixed enums always use an underlying type of 'int'.
9587 unsigned DiagID = 0;
9588 if (SignedEnum && !SignedBitfield) {
9589 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9590 } else if (SignedBitfield && !SignedEnum &&
9591 ED->getNumPositiveBits() == FieldWidth) {
9592 DiagID = diag::warn_signed_bitfield_enum_conversion;
9593 }
9594
9595 if (DiagID) {
9596 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9597 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9598 SourceRange TypeRange =
9599 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9600 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9601 << SignedEnum << TypeRange;
9602 }
9603
9604 // Compute the required bitwidth. If the enum has negative values, we need
9605 // one more bit than the normal number of positive bits to represent the
9606 // sign bit.
9607 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9608 ED->getNumNegativeBits())
9609 : ED->getNumPositiveBits();
9610
9611 // Check the bitwidth.
9612 if (BitsNeeded > FieldWidth) {
9613 Expr *WidthExpr = Bitfield->getBitWidth();
9614 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9615 << Bitfield << ED;
9616 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9617 << BitsNeeded << ED << WidthExpr->getSourceRange();
9618 }
9619 }
9620
John McCall1f425642010-11-11 03:21:53 +00009621 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009622 }
John McCall1f425642010-11-11 03:21:53 +00009623
John McCall1f425642010-11-11 03:21:53 +00009624 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009625
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009626 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009627 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009628 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9629 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009630
John McCall1f425642010-11-11 03:21:53 +00009631 if (OriginalWidth <= FieldWidth)
9632 return false;
9633
Eli Friedmanc267a322012-01-26 23:11:39 +00009634 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009635 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009636 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009637
Eli Friedmanc267a322012-01-26 23:11:39 +00009638 // Check whether the stored value is equal to the original value.
9639 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009640 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009641 return false;
9642
Eli Friedmanc267a322012-01-26 23:11:39 +00009643 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009644 // therefore don't strictly fit into a signed bitfield of width 1.
9645 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009646 return false;
9647
John McCall1f425642010-11-11 03:21:53 +00009648 std::string PrettyValue = Value.toString(10);
9649 std::string PrettyTrunc = TruncatedValue.toString(10);
9650
9651 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9652 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9653 << Init->getSourceRange();
9654
9655 return true;
9656}
9657
John McCalld2a53122010-11-09 23:24:47 +00009658/// Analyze the given simple or compound assignment for warning-worthy
9659/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009660static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009661 // Just recurse on the LHS.
9662 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9663
9664 // We want to recurse on the RHS as normal unless we're assigning to
9665 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009666 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009667 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009668 E->getOperatorLoc())) {
9669 // Recurse, ignoring any implicit conversions on the RHS.
9670 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9671 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009672 }
9673 }
9674
9675 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9676}
9677
John McCall263a48b2010-01-04 23:31:57 +00009678/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009679static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9680 SourceLocation CContext, unsigned diag,
9681 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009682 if (pruneControlFlow) {
9683 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9684 S.PDiag(diag)
9685 << SourceType << T << E->getSourceRange()
9686 << SourceRange(CContext));
9687 return;
9688 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009689 S.Diag(E->getExprLoc(), diag)
9690 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9691}
9692
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009693/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009694static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9695 SourceLocation CContext,
9696 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009697 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009698}
9699
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009700/// Analyze the given compound assignment for the possible losing of
9701/// floating-point precision.
9702static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9703 assert(isa<CompoundAssignOperator>(E) &&
9704 "Must be compound assignment operation");
9705 // Recurse on the LHS and RHS in here
9706 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9707 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9708
9709 // Now check the outermost expression
9710 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9711 const auto *RBT = cast<CompoundAssignOperator>(E)
9712 ->getComputationResultType()
9713 ->getAs<BuiltinType>();
9714
9715 // If both source and target are floating points.
9716 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9717 // Builtin FP kinds are ordered by increasing FP rank.
9718 if (ResultBT->getKind() < RBT->getKind())
9719 // We don't want to warn for system macro.
9720 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9721 // warn about dropping FP rank.
9722 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9723 E->getOperatorLoc(),
9724 diag::warn_impcast_float_result_precision);
9725}
Richard Trieube234c32016-04-21 21:04:55 +00009726
9727/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009728static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9729 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009730 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009731 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009732
9733 Expr *InnerE = E->IgnoreParenImpCasts();
9734 // We also want to warn on, e.g., "int i = -1.234"
9735 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9736 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9737 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9738
9739 const bool IsLiteral =
9740 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9741
9742 llvm::APFloat Value(0.0);
9743 bool IsConstant =
9744 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9745 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009746 return DiagnoseImpCast(S, E, T, CContext,
9747 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009748 }
9749
Chandler Carruth016ef402011-04-10 08:36:24 +00009750 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009751
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009752 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9753 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009754 llvm::APFloat::opStatus Result = Value.convertToInteger(
9755 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9756
9757 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009758 if (IsLiteral) return;
9759 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9760 PruneWarnings);
9761 }
9762
Erich Keanea4c48c62018-05-08 21:26:21 +00009763 // Conversion of a floating-point value to a non-bool integer where the
9764 // integral part cannot be represented by the integer type is undefined.
9765 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9766 return DiagnoseImpCast(
9767 S, E, T, CContext,
9768 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009769 : diag::warn_impcast_float_to_integer_out_of_range,
9770 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009771
Richard Trieube234c32016-04-21 21:04:55 +00009772 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009773 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009774 // Warn on floating point literal to integer.
9775 DiagID = diag::warn_impcast_literal_float_to_integer;
9776 } else if (IntegerValue == 0) {
9777 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9778 return DiagnoseImpCast(S, E, T, CContext,
9779 diag::warn_impcast_float_integer, PruneWarnings);
9780 }
9781 // Warn on non-zero to zero conversion.
9782 DiagID = diag::warn_impcast_float_to_integer_zero;
9783 } else {
9784 if (IntegerValue.isUnsigned()) {
9785 if (!IntegerValue.isMaxValue()) {
9786 return DiagnoseImpCast(S, E, T, CContext,
9787 diag::warn_impcast_float_integer, PruneWarnings);
9788 }
9789 } else { // IntegerValue.isSigned()
9790 if (!IntegerValue.isMaxSignedValue() &&
9791 !IntegerValue.isMinSignedValue()) {
9792 return DiagnoseImpCast(S, E, T, CContext,
9793 diag::warn_impcast_float_integer, PruneWarnings);
9794 }
9795 }
9796 // Warn on evaluatable floating point expression to integer conversion.
9797 DiagID = diag::warn_impcast_float_to_integer;
9798 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009799
Eli Friedman07185912013-08-29 23:44:43 +00009800 // FIXME: Force the precision of the source value down so we don't print
9801 // digits which are usually useless (we don't really care here if we
9802 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9803 // would automatically print the shortest representation, but it's a bit
9804 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009805 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009806 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9807 precision = (precision * 59 + 195) / 196;
9808 Value.toString(PrettySourceValue, precision);
9809
David Blaikie9b88cc02012-05-15 17:18:27 +00009810 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009811 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009812 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009813 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009814 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009815
Richard Trieube234c32016-04-21 21:04:55 +00009816 if (PruneWarnings) {
9817 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9818 S.PDiag(DiagID)
9819 << E->getType() << T.getUnqualifiedType()
9820 << PrettySourceValue << PrettyTargetValue
9821 << E->getSourceRange() << SourceRange(CContext));
9822 } else {
9823 S.Diag(E->getExprLoc(), DiagID)
9824 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9825 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9826 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009827}
9828
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009829static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9830 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009831 if (!Range.Width) return "0";
9832
9833 llvm::APSInt ValueInRange = Value;
9834 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009835 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009836 return ValueInRange.toString(10);
9837}
9838
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009839static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009840 if (!isa<ImplicitCastExpr>(Ex))
9841 return false;
9842
9843 Expr *InnerE = Ex->IgnoreParenImpCasts();
9844 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9845 const Type *Source =
9846 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9847 if (Target->isDependentType())
9848 return false;
9849
9850 const BuiltinType *FloatCandidateBT =
9851 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9852 const Type *BoolCandidateType = ToBool ? Target : Source;
9853
9854 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9855 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9856}
9857
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009858static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9859 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009860 unsigned NumArgs = TheCall->getNumArgs();
9861 for (unsigned i = 0; i < NumArgs; ++i) {
9862 Expr *CurrA = TheCall->getArg(i);
9863 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9864 continue;
9865
9866 bool IsSwapped = ((i > 0) &&
9867 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9868 IsSwapped |= ((i < (NumArgs - 1)) &&
9869 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9870 if (IsSwapped) {
9871 // Warn on this floating-point to bool conversion.
9872 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9873 CurrA->getType(), CC,
9874 diag::warn_impcast_floating_point_to_bool);
9875 }
9876 }
9877}
9878
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009879static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9880 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009881 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9882 E->getExprLoc()))
9883 return;
9884
Richard Trieu09d6b802016-01-08 23:35:06 +00009885 // Don't warn on functions which have return type nullptr_t.
9886 if (isa<CallExpr>(E))
9887 return;
9888
Richard Trieu5b993502014-10-15 03:42:06 +00009889 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9890 const Expr::NullPointerConstantKind NullKind =
9891 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9892 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9893 return;
9894
9895 // Return if target type is a safe conversion.
9896 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9897 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9898 return;
9899
9900 SourceLocation Loc = E->getSourceRange().getBegin();
9901
Richard Trieu0a5e1662016-02-13 00:58:53 +00009902 // Venture through the macro stacks to get to the source of macro arguments.
9903 // The new location is a better location than the complete location that was
9904 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009905 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9906 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009907
Richard Trieu5b993502014-10-15 03:42:06 +00009908 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009909 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9910 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9911 Loc, S.SourceMgr, S.getLangOpts());
9912 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +00009913 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +00009914 }
9915
9916 // Only warn if the null and context location are in the same macro expansion.
9917 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9918 return;
9919
9920 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009921 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009922 << FixItHint::CreateReplacement(Loc,
9923 S.getFixItZeroLiteralForType(T, Loc));
9924}
9925
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009926static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9927 ObjCArrayLiteral *ArrayLiteral);
9928
9929static void
9930checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9931 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009932
9933/// Check a single element within a collection literal against the
9934/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009935static void checkObjCCollectionLiteralElement(Sema &S,
9936 QualType TargetElementType,
9937 Expr *Element,
9938 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009939 // Skip a bitcast to 'id' or qualified 'id'.
9940 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9941 if (ICE->getCastKind() == CK_BitCast &&
9942 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9943 Element = ICE->getSubExpr();
9944 }
9945
9946 QualType ElementType = Element->getType();
9947 ExprResult ElementResult(Element);
9948 if (ElementType->getAs<ObjCObjectPointerType>() &&
9949 S.CheckSingleAssignmentConstraints(TargetElementType,
9950 ElementResult,
9951 false, false)
9952 != Sema::Compatible) {
9953 S.Diag(Element->getLocStart(),
9954 diag::warn_objc_collection_literal_element)
9955 << ElementType << ElementKind << TargetElementType
9956 << Element->getSourceRange();
9957 }
9958
9959 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9960 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9961 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9962 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9963}
9964
9965/// Check an Objective-C array literal being converted to the given
9966/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009967static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9968 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009969 if (!S.NSArrayDecl)
9970 return;
9971
9972 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9973 if (!TargetObjCPtr)
9974 return;
9975
9976 if (TargetObjCPtr->isUnspecialized() ||
9977 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9978 != S.NSArrayDecl->getCanonicalDecl())
9979 return;
9980
9981 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9982 if (TypeArgs.size() != 1)
9983 return;
9984
9985 QualType TargetElementType = TypeArgs[0];
9986 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9987 checkObjCCollectionLiteralElement(S, TargetElementType,
9988 ArrayLiteral->getElement(I),
9989 0);
9990 }
9991}
9992
9993/// Check an Objective-C dictionary literal being converted to the given
9994/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009995static void
9996checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9997 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009998 if (!S.NSDictionaryDecl)
9999 return;
10000
10001 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10002 if (!TargetObjCPtr)
10003 return;
10004
10005 if (TargetObjCPtr->isUnspecialized() ||
10006 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10007 != S.NSDictionaryDecl->getCanonicalDecl())
10008 return;
10009
10010 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10011 if (TypeArgs.size() != 2)
10012 return;
10013
10014 QualType TargetKeyType = TypeArgs[0];
10015 QualType TargetObjectType = TypeArgs[1];
10016 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10017 auto Element = DictionaryLiteral->getKeyValueElement(I);
10018 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10019 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10020 }
10021}
10022
Richard Trieufc404c72016-02-05 23:02:38 +000010023// Helper function to filter out cases for constant width constant conversion.
10024// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010025static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10026 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010027 // If initializing from a constant, and the constant starts with '0',
10028 // then it is a binary, octal, or hexadecimal. Allow these constants
10029 // to fill all the bits, even if there is a sign change.
10030 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10031 const char FirstLiteralCharacter =
10032 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10033 if (FirstLiteralCharacter == '0')
10034 return false;
10035 }
10036
10037 // If the CC location points to a '{', and the type is char, then assume
10038 // assume it is an array initialization.
10039 if (CC.isValid() && T->isCharType()) {
10040 const char FirstContextCharacter =
10041 S.getSourceManager().getCharacterData(CC)[0];
10042 if (FirstContextCharacter == '{')
10043 return false;
10044 }
10045
10046 return true;
10047}
10048
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010049static void
10050CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10051 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010052 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010053
John McCallcc7e5bf2010-05-06 08:58:33 +000010054 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10055 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10056 if (Source == Target) return;
10057 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010058
Chandler Carruthc22845a2011-07-26 05:40:03 +000010059 // If the conversion context location is invalid don't complain. We also
10060 // don't want to emit a warning if the issue occurs from the expansion of
10061 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10062 // delay this check as long as possible. Once we detect we are in that
10063 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010064 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010065 return;
10066
Richard Trieu021baa32011-09-23 20:10:00 +000010067 // Diagnose implicit casts to bool.
10068 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10069 if (isa<StringLiteral>(E))
10070 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010071 // and expressions, for instance, assert(0 && "error here"), are
10072 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010073 return DiagnoseImpCast(S, E, T, CC,
10074 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010075 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10076 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10077 // This covers the literal expressions that evaluate to Objective-C
10078 // objects.
10079 return DiagnoseImpCast(S, E, T, CC,
10080 diag::warn_impcast_objective_c_literal_to_bool);
10081 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010082 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10083 // Warn on pointer to bool conversion that is always true.
10084 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10085 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010086 }
Richard Trieu021baa32011-09-23 20:10:00 +000010087 }
John McCall263a48b2010-01-04 23:31:57 +000010088
Douglas Gregor5054cb02015-07-07 03:58:22 +000010089 // Check implicit casts from Objective-C collection literals to specialized
10090 // collection types, e.g., NSArray<NSString *> *.
10091 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10092 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10093 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10094 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10095
John McCall263a48b2010-01-04 23:31:57 +000010096 // Strip vector types.
10097 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010098 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010099 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010100 return;
John McCallacf0ee52010-10-08 02:01:28 +000010101 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010102 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010103
Chris Lattneree7286f2011-06-14 04:51:15 +000010104 // If the vector cast is cast between two vectors of the same size, it is
10105 // a bitcast, not a conversion.
10106 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10107 return;
John McCall263a48b2010-01-04 23:31:57 +000010108
10109 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10110 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10111 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010112 if (auto VecTy = dyn_cast<VectorType>(Target))
10113 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010114
10115 // Strip complex types.
10116 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010117 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010118 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010119 return;
10120
Tim Northover02416372017-08-08 23:18:05 +000010121 return DiagnoseImpCast(S, E, T, CC,
10122 S.getLangOpts().CPlusPlus
10123 ? diag::err_impcast_complex_scalar
10124 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010125 }
John McCall263a48b2010-01-04 23:31:57 +000010126
10127 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10128 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10129 }
10130
10131 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10132 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10133
10134 // If the source is floating point...
10135 if (SourceBT && SourceBT->isFloatingPoint()) {
10136 // ...and the target is floating point...
10137 if (TargetBT && TargetBT->isFloatingPoint()) {
10138 // ...then warn if we're dropping FP rank.
10139
10140 // Builtin FP kinds are ordered by increasing FP rank.
10141 if (SourceBT->getKind() > TargetBT->getKind()) {
10142 // Don't warn about float constants that are precisely
10143 // representable in the target type.
10144 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010145 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010146 // Value might be a float, a float vector, or a float complex.
10147 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010148 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10149 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010150 return;
10151 }
10152
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010153 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010154 return;
10155
John McCallacf0ee52010-10-08 02:01:28 +000010156 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010157 }
10158 // ... or possibly if we're increasing rank, too
10159 else if (TargetBT->getKind() > SourceBT->getKind()) {
10160 if (S.SourceMgr.isInSystemMacro(CC))
10161 return;
10162
10163 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010164 }
10165 return;
10166 }
10167
Richard Trieube234c32016-04-21 21:04:55 +000010168 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010169 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010170 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010171 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010172
Richard Trieube234c32016-04-21 21:04:55 +000010173 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010174 }
John McCall263a48b2010-01-04 23:31:57 +000010175
Richard Smith54894fd2015-12-30 01:06:52 +000010176 // Detect the case where a call result is converted from floating-point to
10177 // to bool, and the final argument to the call is converted from bool, to
10178 // discover this typo:
10179 //
10180 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10181 //
10182 // FIXME: This is an incredibly special case; is there some more general
10183 // way to detect this class of misplaced-parentheses bug?
10184 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010185 // Check last argument of function call to see if it is an
10186 // implicit cast from a type matching the type the result
10187 // is being cast to.
10188 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010189 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010190 Expr *LastA = CEx->getArg(NumArgs - 1);
10191 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010192 if (isa<ImplicitCastExpr>(LastA) &&
10193 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010194 // Warn on this floating-point to bool conversion
10195 DiagnoseImpCast(S, E, T, CC,
10196 diag::warn_impcast_floating_point_to_bool);
10197 }
10198 }
10199 }
John McCall263a48b2010-01-04 23:31:57 +000010200 return;
10201 }
10202
Richard Trieu5b993502014-10-15 03:42:06 +000010203 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010204
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010205 S.DiscardMisalignedMemberAddress(Target, E);
10206
David Blaikie9366d2b2012-06-19 21:19:06 +000010207 if (!Source->isIntegerType() || !Target->isIntegerType())
10208 return;
10209
David Blaikie7555b6a2012-05-15 16:56:36 +000010210 // TODO: remove this early return once the false positives for constant->bool
10211 // in templates, macros, etc, are reduced or removed.
10212 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10213 return;
10214
John McCallcc7e5bf2010-05-06 08:58:33 +000010215 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010216 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010217
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010218 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010219 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010220 // TODO: this should happen for bitfield stores, too.
10221 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010222 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010223 if (S.SourceMgr.isInSystemMacro(CC))
10224 return;
10225
John McCall18a2c2c2010-11-09 22:22:12 +000010226 std::string PrettySourceValue = Value.toString(10);
10227 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010228
Ted Kremenek33ba9952011-10-22 02:37:33 +000010229 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10230 S.PDiag(diag::warn_impcast_integer_precision_constant)
10231 << PrettySourceValue << PrettyTargetValue
10232 << E->getType() << T << E->getSourceRange()
10233 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010234 return;
10235 }
10236
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010237 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10238 if (S.SourceMgr.isInSystemMacro(CC))
10239 return;
10240
David Blaikie9455da02012-04-12 22:40:54 +000010241 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010242 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10243 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010244 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010245 }
10246
Richard Trieudcb55572016-01-29 23:51:16 +000010247 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10248 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10249 // Warn when doing a signed to signed conversion, warn if the positive
10250 // source value is exactly the width of the target type, which will
10251 // cause a negative value to be stored.
10252
10253 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010254 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10255 !S.SourceMgr.isInSystemMacro(CC)) {
10256 if (isSameWidthConstantConversion(S, E, T, CC)) {
10257 std::string PrettySourceValue = Value.toString(10);
10258 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010259
Richard Trieufc404c72016-02-05 23:02:38 +000010260 S.DiagRuntimeBehavior(
10261 E->getExprLoc(), E,
10262 S.PDiag(diag::warn_impcast_integer_precision_constant)
10263 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10264 << E->getSourceRange() << clang::SourceRange(CC));
10265 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010266 }
10267 }
Richard Trieufc404c72016-02-05 23:02:38 +000010268
Richard Trieudcb55572016-01-29 23:51:16 +000010269 // Fall through for non-constants to give a sign conversion warning.
10270 }
10271
John McCallcc7e5bf2010-05-06 08:58:33 +000010272 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10273 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10274 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010275 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010276 return;
10277
John McCallcc7e5bf2010-05-06 08:58:33 +000010278 unsigned DiagID = diag::warn_impcast_integer_sign;
10279
10280 // Traditionally, gcc has warned about this under -Wsign-compare.
10281 // We also want to warn about it in -Wconversion.
10282 // So if -Wconversion is off, use a completely identical diagnostic
10283 // in the sign-compare group.
10284 // The conditional-checking code will
10285 if (ICContext) {
10286 DiagID = diag::warn_impcast_integer_sign_conditional;
10287 *ICContext = true;
10288 }
10289
John McCallacf0ee52010-10-08 02:01:28 +000010290 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010291 }
10292
Douglas Gregora78f1932011-02-22 02:45:07 +000010293 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010294 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10295 // type, to give us better diagnostics.
10296 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010297 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010298 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10299 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10300 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10301 SourceType = S.Context.getTypeDeclType(Enum);
10302 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10303 }
10304 }
10305
Douglas Gregora78f1932011-02-22 02:45:07 +000010306 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10307 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010308 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10309 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010310 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010311 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010312 return;
10313
Douglas Gregor364f7db2011-03-12 00:14:31 +000010314 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010315 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010316 }
John McCall263a48b2010-01-04 23:31:57 +000010317}
10318
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010319static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10320 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010321
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010322static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10323 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010324 E = E->IgnoreParenImpCasts();
10325
10326 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010327 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010328
John McCallacf0ee52010-10-08 02:01:28 +000010329 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010330 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010331 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010332}
10333
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010334static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10335 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010336 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010337
10338 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010339 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10340 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010341
10342 // If -Wconversion would have warned about either of the candidates
10343 // for a signedness conversion to the context type...
10344 if (!Suspicious) return;
10345
10346 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010347 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010348 return;
10349
John McCallcc7e5bf2010-05-06 08:58:33 +000010350 // ...then check whether it would have warned about either of the
10351 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010352 if (E->getType() == T) return;
10353
10354 Suspicious = false;
10355 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10356 E->getType(), CC, &Suspicious);
10357 if (!Suspicious)
10358 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010359 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010360}
10361
Richard Trieu65724892014-11-15 06:37:39 +000010362/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10363/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010364static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010365 if (S.getLangOpts().Bool)
10366 return;
10367 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10368}
10369
John McCallcc7e5bf2010-05-06 08:58:33 +000010370/// AnalyzeImplicitConversions - Find and report any interesting
10371/// implicit conversions in the given expression. There are a couple
10372/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010373static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10374 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010375 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010376 Expr *E = OrigE->IgnoreParenImpCasts();
10377
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010378 if (E->isTypeDependent() || E->isValueDependent())
10379 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010380
John McCallcc7e5bf2010-05-06 08:58:33 +000010381 // For conditional operators, we analyze the arguments as if they
10382 // were being fed directly into the output.
10383 if (isa<ConditionalOperator>(E)) {
10384 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010385 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010386 return;
10387 }
10388
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010389 // Check implicit argument conversions for function calls.
10390 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10391 CheckImplicitArgumentConversions(S, Call, CC);
10392
John McCallcc7e5bf2010-05-06 08:58:33 +000010393 // Go ahead and check any implicit conversions we might have skipped.
10394 // The non-canonical typecheck is just an optimization;
10395 // CheckImplicitConversion will filter out dead implicit conversions.
10396 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010397 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010398
10399 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010400
10401 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10402 // The bound subexpressions in a PseudoObjectExpr are not reachable
10403 // as transitive children.
10404 // FIXME: Use a more uniform representation for this.
10405 for (auto *SE : POE->semantics())
10406 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10407 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010408 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010409
John McCallcc7e5bf2010-05-06 08:58:33 +000010410 // Skip past explicit casts.
10411 if (isa<ExplicitCastExpr>(E)) {
10412 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010413 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010414 }
10415
John McCalld2a53122010-11-09 23:24:47 +000010416 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10417 // Do a somewhat different check with comparison operators.
10418 if (BO->isComparisonOp())
10419 return AnalyzeComparison(S, BO);
10420
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010421 // And with simple assignments.
10422 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010423 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010424 // And with compound assignments.
10425 if (BO->isAssignmentOp())
10426 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010427 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010428
10429 // These break the otherwise-useful invariant below. Fortunately,
10430 // we don't really need to recurse into them, because any internal
10431 // expressions should have been analyzed already when they were
10432 // built into statements.
10433 if (isa<StmtExpr>(E)) return;
10434
10435 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010436 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010437
10438 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010439 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010440 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010441 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010442 for (Stmt *SubStmt : E->children()) {
10443 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010444 if (!ChildExpr)
10445 continue;
10446
Richard Trieu955231d2014-01-25 01:10:35 +000010447 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010448 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010449 // Ignore checking string literals that are in logical and operators.
10450 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010451 continue;
10452 AnalyzeImplicitConversions(S, ChildExpr, CC);
10453 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010454
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010455 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010456 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10457 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010458 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010459
10460 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10461 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010462 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010463 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010464
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010465 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10466 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010467 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010468}
10469
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010470/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010471static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10472 // Taking into account implicit conversions,
10473 // allow any integer.
10474 if (!E->getType()->isIntegerType()) {
10475 S.Diag(E->getLocStart(),
10476 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10477 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010478 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010479 // Potentially emit standard warnings for implicit conversions if enabled
10480 // using -Wconversion.
10481 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10482 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010483}
10484
Richard Trieuc1888e02014-06-28 23:25:37 +000010485// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10486// Returns true when emitting a warning about taking the address of a reference.
10487static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010488 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010489 E = E->IgnoreParenImpCasts();
10490
10491 const FunctionDecl *FD = nullptr;
10492
10493 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10494 if (!DRE->getDecl()->getType()->isReferenceType())
10495 return false;
10496 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10497 if (!M->getMemberDecl()->getType()->isReferenceType())
10498 return false;
10499 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010500 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010501 return false;
10502 FD = Call->getDirectCallee();
10503 } else {
10504 return false;
10505 }
10506
10507 SemaRef.Diag(E->getExprLoc(), PD);
10508
10509 // If possible, point to location of function.
10510 if (FD) {
10511 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10512 }
10513
10514 return true;
10515}
10516
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010517// Returns true if the SourceLocation is expanded from any macro body.
10518// Returns false if the SourceLocation is invalid, is from not in a macro
10519// expansion, or is from expanded from a top-level macro argument.
10520static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10521 if (Loc.isInvalid())
10522 return false;
10523
10524 while (Loc.isMacroID()) {
10525 if (SM.isMacroBodyExpansion(Loc))
10526 return true;
10527 Loc = SM.getImmediateMacroCallerLoc(Loc);
10528 }
10529
10530 return false;
10531}
10532
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010533/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010534/// \param E the expression containing the pointer
10535/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10536/// compared to a null pointer
10537/// \param IsEqual True when the comparison is equal to a null pointer
10538/// \param Range Extra SourceRange to highlight in the diagnostic
10539void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10540 Expr::NullPointerConstantKind NullKind,
10541 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010542 if (!E)
10543 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010544
10545 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010546 if (E->getExprLoc().isMacroID()) {
10547 const SourceManager &SM = getSourceManager();
10548 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10549 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010550 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010551 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010552 E = E->IgnoreImpCasts();
10553
10554 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10555
Richard Trieuf7432752014-06-06 21:39:26 +000010556 if (isa<CXXThisExpr>(E)) {
10557 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10558 : diag::warn_this_bool_conversion;
10559 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10560 return;
10561 }
10562
Richard Trieu3bb8b562014-02-26 02:36:06 +000010563 bool IsAddressOf = false;
10564
10565 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10566 if (UO->getOpcode() != UO_AddrOf)
10567 return;
10568 IsAddressOf = true;
10569 E = UO->getSubExpr();
10570 }
10571
Richard Trieuc1888e02014-06-28 23:25:37 +000010572 if (IsAddressOf) {
10573 unsigned DiagID = IsCompare
10574 ? diag::warn_address_of_reference_null_compare
10575 : diag::warn_address_of_reference_bool_conversion;
10576 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10577 << IsEqual;
10578 if (CheckForReference(*this, E, PD)) {
10579 return;
10580 }
10581 }
10582
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010583 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10584 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010585 std::string Str;
10586 llvm::raw_string_ostream S(Str);
10587 E->printPretty(S, nullptr, getPrintingPolicy());
10588 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10589 : diag::warn_cast_nonnull_to_bool;
10590 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10591 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010592 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010593 };
10594
10595 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10596 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10597 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010598 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10599 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010600 return;
10601 }
10602 }
10603 }
10604
Richard Trieu3bb8b562014-02-26 02:36:06 +000010605 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010606 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010607 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10608 D = R->getDecl();
10609 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10610 D = M->getMemberDecl();
10611 }
10612
10613 // Weak Decls can be null.
10614 if (!D || D->isWeak())
10615 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010616
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010617 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010618 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10619 if (getCurFunction() &&
10620 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010621 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10622 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010623 return;
10624 }
10625
10626 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010627 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010628 assert(ParamIter != FD->param_end());
10629 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10630
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010631 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10632 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010633 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010634 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010635 }
George Burgess IV850269a2015-12-08 22:02:00 +000010636
Joel E. Denny81508102018-03-13 14:51:22 +000010637 for (const ParamIdx &ArgNo : NonNull->args()) {
10638 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010639 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010640 return;
10641 }
George Burgess IV850269a2015-12-08 22:02:00 +000010642 }
10643 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010644 }
10645 }
George Burgess IV850269a2015-12-08 22:02:00 +000010646 }
10647
Richard Trieu3bb8b562014-02-26 02:36:06 +000010648 QualType T = D->getType();
10649 const bool IsArray = T->isArrayType();
10650 const bool IsFunction = T->isFunctionType();
10651
Richard Trieuc1888e02014-06-28 23:25:37 +000010652 // Address of function is used to silence the function warning.
10653 if (IsAddressOf && IsFunction) {
10654 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010655 }
10656
10657 // Found nothing.
10658 if (!IsAddressOf && !IsFunction && !IsArray)
10659 return;
10660
10661 // Pretty print the expression for the diagnostic.
10662 std::string Str;
10663 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010664 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010665
10666 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10667 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010668 enum {
10669 AddressOf,
10670 FunctionPointer,
10671 ArrayPointer
10672 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010673 if (IsAddressOf)
10674 DiagType = AddressOf;
10675 else if (IsFunction)
10676 DiagType = FunctionPointer;
10677 else if (IsArray)
10678 DiagType = ArrayPointer;
10679 else
10680 llvm_unreachable("Could not determine diagnostic.");
10681 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10682 << Range << IsEqual;
10683
10684 if (!IsFunction)
10685 return;
10686
10687 // Suggest '&' to silence the function warning.
10688 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10689 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10690
10691 // Check to see if '()' fixit should be emitted.
10692 QualType ReturnType;
10693 UnresolvedSet<4> NonTemplateOverloads;
10694 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10695 if (ReturnType.isNull())
10696 return;
10697
10698 if (IsCompare) {
10699 // There are two cases here. If there is null constant, the only suggest
10700 // for a pointer return type. If the null is 0, then suggest if the return
10701 // type is a pointer or an integer type.
10702 if (!ReturnType->isPointerType()) {
10703 if (NullKind == Expr::NPCK_ZeroExpression ||
10704 NullKind == Expr::NPCK_ZeroLiteral) {
10705 if (!ReturnType->isIntegerType())
10706 return;
10707 } else {
10708 return;
10709 }
10710 }
10711 } else { // !IsCompare
10712 // For function to bool, only suggest if the function pointer has bool
10713 // return type.
10714 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10715 return;
10716 }
10717 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010718 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010719}
10720
John McCallcc7e5bf2010-05-06 08:58:33 +000010721/// Diagnoses "dangerous" implicit conversions within the given
10722/// expression (which is a full expression). Implements -Wconversion
10723/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010724///
10725/// \param CC the "context" location of the implicit conversion, i.e.
10726/// the most location of the syntactic entity requiring the implicit
10727/// conversion
10728void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010729 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010730 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010731 return;
10732
10733 // Don't diagnose for value- or type-dependent expressions.
10734 if (E->isTypeDependent() || E->isValueDependent())
10735 return;
10736
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010737 // Check for array bounds violations in cases where the check isn't triggered
10738 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10739 // ArraySubscriptExpr is on the RHS of a variable initialization.
10740 CheckArrayAccess(E);
10741
John McCallacf0ee52010-10-08 02:01:28 +000010742 // This is not the right CC for (e.g.) a variable initialization.
10743 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010744}
10745
Richard Trieu65724892014-11-15 06:37:39 +000010746/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10747/// Input argument E is a logical expression.
10748void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10749 ::CheckBoolLikeConversion(*this, E, CC);
10750}
10751
Richard Smith9f7df0c2017-06-26 23:19:32 +000010752/// Diagnose when expression is an integer constant expression and its evaluation
10753/// results in integer overflow
10754void Sema::CheckForIntOverflow (Expr *E) {
10755 // Use a work list to deal with nested struct initializers.
10756 SmallVector<Expr *, 2> Exprs(1, E);
10757
10758 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010759 Expr *OriginalE = Exprs.pop_back_val();
10760 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010761
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010762 if (isa<BinaryOperator>(E)) {
10763 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010764 continue;
10765 }
10766
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010767 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010768 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010769 else if (isa<ObjCBoxedExpr>(OriginalE))
10770 E->EvaluateForOverflow(Context);
10771 else if (auto Call = dyn_cast<CallExpr>(E))
10772 Exprs.append(Call->arg_begin(), Call->arg_end());
10773 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10774 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010775 } while (!Exprs.empty());
10776}
10777
Richard Smithc406cb72013-01-17 01:17:56 +000010778namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010779
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010780/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010781/// same object.
10782class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010783 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010784
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010785 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010786 /// unsequenced if one is an ancestor or a descendent of the other. When we
10787 /// finish processing an expression with sequencing, such as a comma
10788 /// expression, we fold its tree nodes into its parent, since they are
10789 /// unsequenced with respect to nodes we will visit later.
10790 class SequenceTree {
10791 struct Value {
10792 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10793 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010794 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010795 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010796 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010797
10798 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010799 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010800 /// to some other region.
10801 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010802 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010803
10804 unsigned Index = 0;
10805
10806 explicit Seq(unsigned N) : Index(N) {}
10807
Richard Smithc406cb72013-01-17 01:17:56 +000010808 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010809 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010810 };
10811
10812 SequenceTree() { Values.push_back(Value(0)); }
10813 Seq root() const { return Seq(0); }
10814
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010815 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010816 /// subset of \p Parent. This sequence of operations is sequenced with
10817 /// respect to other children of \p Parent.
10818 Seq allocate(Seq Parent) {
10819 Values.push_back(Value(Parent.Index));
10820 return Seq(Values.size() - 1);
10821 }
10822
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010823 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010824 void merge(Seq S) {
10825 Values[S.Index].Merged = true;
10826 }
10827
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010828 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010829 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10830 /// should have been merged into its parent as appropriate.
10831 bool isUnsequenced(Seq Cur, Seq Old) {
10832 unsigned C = representative(Cur.Index);
10833 unsigned Target = representative(Old.Index);
10834 while (C >= Target) {
10835 if (C == Target)
10836 return true;
10837 C = Values[C].Parent;
10838 }
10839 return false;
10840 }
10841
10842 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010843 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010844 unsigned representative(unsigned K) {
10845 if (Values[K].Merged)
10846 // Perform path compression as we go.
10847 return Values[K].Parent = representative(Values[K].Parent);
10848 return K;
10849 }
10850 };
10851
10852 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010853 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010854
10855 /// Different flavors of object usage which we track. We only track the
10856 /// least-sequenced usage of each kind.
10857 enum UsageKind {
10858 /// A read of an object. Multiple unsequenced reads are OK.
10859 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010860
Richard Smithc406cb72013-01-17 01:17:56 +000010861 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010862 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010863 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010864
Richard Smithc406cb72013-01-17 01:17:56 +000010865 /// A modification of an object which is not sequenced before the value
10866 /// computation of the expression, such as n++.
10867 UK_ModAsSideEffect,
10868
10869 UK_Count = UK_ModAsSideEffect + 1
10870 };
10871
10872 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010873 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010874 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010875
10876 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010877 };
10878
10879 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010880 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010881
Richard Smithc406cb72013-01-17 01:17:56 +000010882 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010883 bool Diagnosed = false;
10884
10885 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010886 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010887 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010888
10889 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010890
Richard Smithc406cb72013-01-17 01:17:56 +000010891 /// Sequenced regions within the expression.
10892 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010893
Richard Smithc406cb72013-01-17 01:17:56 +000010894 /// Declaration modifications and references which we have seen.
10895 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010896
Richard Smithc406cb72013-01-17 01:17:56 +000010897 /// The region we are currently within.
10898 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010899
Richard Smithc406cb72013-01-17 01:17:56 +000010900 /// Filled in with declarations which were modified as a side-effect
10901 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010902 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10903
Richard Smithd33f5202013-01-17 23:18:09 +000010904 /// Expressions to check later. We defer checking these to reduce
10905 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010906 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010907
10908 /// RAII object wrapping the visitation of a sequenced subexpression of an
10909 /// expression. At the end of this process, the side-effects of the evaluation
10910 /// become sequenced with respect to the value computation of the result, so
10911 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10912 /// UK_ModAsValue.
10913 struct SequencedSubexpression {
10914 SequencedSubexpression(SequenceChecker &Self)
10915 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10916 Self.ModAsSideEffect = &ModAsSideEffect;
10917 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010918
Richard Smithc406cb72013-01-17 01:17:56 +000010919 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010920 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10921 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010922 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010923 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10924 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010925 }
10926 Self.ModAsSideEffect = OldModAsSideEffect;
10927 }
10928
10929 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010930 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010931 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010932 };
10933
Richard Smith40238f02013-06-20 22:21:56 +000010934 /// RAII object wrapping the visitation of a subexpression which we might
10935 /// choose to evaluate as a constant. If any subexpression is evaluated and
10936 /// found to be non-constant, this allows us to suppress the evaluation of
10937 /// the outer expression.
10938 class EvaluationTracker {
10939 public:
10940 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010941 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010942 Self.EvalTracker = this;
10943 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010944
Richard Smith40238f02013-06-20 22:21:56 +000010945 ~EvaluationTracker() {
10946 Self.EvalTracker = Prev;
10947 if (Prev)
10948 Prev->EvalOK &= EvalOK;
10949 }
10950
10951 bool evaluate(const Expr *E, bool &Result) {
10952 if (!EvalOK || E->isValueDependent())
10953 return false;
10954 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10955 return EvalOK;
10956 }
10957
10958 private:
10959 SequenceChecker &Self;
10960 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010961 bool EvalOK = true;
10962 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010963
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010964 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000010965 /// if any.
10966 Object getObject(Expr *E, bool Mod) const {
10967 E = E->IgnoreParenCasts();
10968 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10969 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10970 return getObject(UO->getSubExpr(), Mod);
10971 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10972 if (BO->getOpcode() == BO_Comma)
10973 return getObject(BO->getRHS(), Mod);
10974 if (Mod && BO->isAssignmentOp())
10975 return getObject(BO->getLHS(), Mod);
10976 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10977 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10978 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10979 return ME->getMemberDecl();
10980 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10981 // FIXME: If this is a reference, map through to its value.
10982 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010983 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010984 }
10985
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010986 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000010987 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10988 Usage &U = UI.Uses[UK];
10989 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10990 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10991 ModAsSideEffect->push_back(std::make_pair(O, U));
10992 U.Use = Ref;
10993 U.Seq = Region;
10994 }
10995 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010996
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010997 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000010998 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10999 bool IsModMod) {
11000 if (UI.Diagnosed)
11001 return;
11002
11003 const Usage &U = UI.Uses[OtherKind];
11004 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11005 return;
11006
11007 Expr *Mod = U.Use;
11008 Expr *ModOrUse = Ref;
11009 if (OtherKind == UK_Use)
11010 std::swap(Mod, ModOrUse);
11011
11012 SemaRef.Diag(Mod->getExprLoc(),
11013 IsModMod ? diag::warn_unsequenced_mod_mod
11014 : diag::warn_unsequenced_mod_use)
11015 << O << SourceRange(ModOrUse->getExprLoc());
11016 UI.Diagnosed = true;
11017 }
11018
11019 void notePreUse(Object O, Expr *Use) {
11020 UsageInfo &U = UsageMap[O];
11021 // Uses conflict with other modifications.
11022 checkUsage(O, U, Use, UK_ModAsValue, false);
11023 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011024
Richard Smithc406cb72013-01-17 01:17:56 +000011025 void notePostUse(Object O, Expr *Use) {
11026 UsageInfo &U = UsageMap[O];
11027 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11028 addUsage(U, O, Use, UK_Use);
11029 }
11030
11031 void notePreMod(Object O, Expr *Mod) {
11032 UsageInfo &U = UsageMap[O];
11033 // Modifications conflict with other modifications and with uses.
11034 checkUsage(O, U, Mod, UK_ModAsValue, true);
11035 checkUsage(O, U, Mod, UK_Use, false);
11036 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011037
Richard Smithc406cb72013-01-17 01:17:56 +000011038 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11039 UsageInfo &U = UsageMap[O];
11040 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11041 addUsage(U, O, Use, UK);
11042 }
11043
11044public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011045 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011046 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011047 Visit(E);
11048 }
11049
11050 void VisitStmt(Stmt *S) {
11051 // Skip all statements which aren't expressions for now.
11052 }
11053
11054 void VisitExpr(Expr *E) {
11055 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011056 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011057 }
11058
11059 void VisitCastExpr(CastExpr *E) {
11060 Object O = Object();
11061 if (E->getCastKind() == CK_LValueToRValue)
11062 O = getObject(E->getSubExpr(), false);
11063
11064 if (O)
11065 notePreUse(O, E);
11066 VisitExpr(E);
11067 if (O)
11068 notePostUse(O, E);
11069 }
11070
11071 void VisitBinComma(BinaryOperator *BO) {
11072 // C++11 [expr.comma]p1:
11073 // Every value computation and side effect associated with the left
11074 // expression is sequenced before every value computation and side
11075 // effect associated with the right expression.
11076 SequenceTree::Seq LHS = Tree.allocate(Region);
11077 SequenceTree::Seq RHS = Tree.allocate(Region);
11078 SequenceTree::Seq OldRegion = Region;
11079
11080 {
11081 SequencedSubexpression SeqLHS(*this);
11082 Region = LHS;
11083 Visit(BO->getLHS());
11084 }
11085
11086 Region = RHS;
11087 Visit(BO->getRHS());
11088
11089 Region = OldRegion;
11090
11091 // Forget that LHS and RHS are sequenced. They are both unsequenced
11092 // with respect to other stuff.
11093 Tree.merge(LHS);
11094 Tree.merge(RHS);
11095 }
11096
11097 void VisitBinAssign(BinaryOperator *BO) {
11098 // The modification is sequenced after the value computation of the LHS
11099 // and RHS, so check it before inspecting the operands and update the
11100 // map afterwards.
11101 Object O = getObject(BO->getLHS(), true);
11102 if (!O)
11103 return VisitExpr(BO);
11104
11105 notePreMod(O, BO);
11106
11107 // C++11 [expr.ass]p7:
11108 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11109 // only once.
11110 //
11111 // Therefore, for a compound assignment operator, O is considered used
11112 // everywhere except within the evaluation of E1 itself.
11113 if (isa<CompoundAssignOperator>(BO))
11114 notePreUse(O, BO);
11115
11116 Visit(BO->getLHS());
11117
11118 if (isa<CompoundAssignOperator>(BO))
11119 notePostUse(O, BO);
11120
11121 Visit(BO->getRHS());
11122
Richard Smith83e37bee2013-06-26 23:16:51 +000011123 // C++11 [expr.ass]p1:
11124 // the assignment is sequenced [...] before the value computation of the
11125 // assignment expression.
11126 // C11 6.5.16/3 has no such rule.
11127 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11128 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011129 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011130
Richard Smithc406cb72013-01-17 01:17:56 +000011131 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11132 VisitBinAssign(CAO);
11133 }
11134
11135 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11136 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11137 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11138 Object O = getObject(UO->getSubExpr(), true);
11139 if (!O)
11140 return VisitExpr(UO);
11141
11142 notePreMod(O, UO);
11143 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011144 // C++11 [expr.pre.incr]p1:
11145 // the expression ++x is equivalent to x+=1
11146 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11147 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011148 }
11149
11150 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11151 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11152 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11153 Object O = getObject(UO->getSubExpr(), true);
11154 if (!O)
11155 return VisitExpr(UO);
11156
11157 notePreMod(O, UO);
11158 Visit(UO->getSubExpr());
11159 notePostMod(O, UO, UK_ModAsSideEffect);
11160 }
11161
11162 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11163 void VisitBinLOr(BinaryOperator *BO) {
11164 // The side-effects of the LHS of an '&&' are sequenced before the
11165 // value computation of the RHS, and hence before the value computation
11166 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11167 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011168 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011169 {
11170 SequencedSubexpression Sequenced(*this);
11171 Visit(BO->getLHS());
11172 }
11173
11174 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011175 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011176 if (!Result)
11177 Visit(BO->getRHS());
11178 } else {
11179 // Check for unsequenced operations in the RHS, treating it as an
11180 // entirely separate evaluation.
11181 //
11182 // FIXME: If there are operations in the RHS which are unsequenced
11183 // with respect to operations outside the RHS, and those operations
11184 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011185 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011186 }
Richard Smithc406cb72013-01-17 01:17:56 +000011187 }
11188 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011189 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011190 {
11191 SequencedSubexpression Sequenced(*this);
11192 Visit(BO->getLHS());
11193 }
11194
11195 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011196 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011197 if (Result)
11198 Visit(BO->getRHS());
11199 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011200 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011201 }
Richard Smithc406cb72013-01-17 01:17:56 +000011202 }
11203
11204 // Only visit the condition, unless we can be sure which subexpression will
11205 // be chosen.
11206 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011207 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011208 {
11209 SequencedSubexpression Sequenced(*this);
11210 Visit(CO->getCond());
11211 }
Richard Smithc406cb72013-01-17 01:17:56 +000011212
11213 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011214 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011215 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011216 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011217 WorkList.push_back(CO->getTrueExpr());
11218 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011219 }
Richard Smithc406cb72013-01-17 01:17:56 +000011220 }
11221
Richard Smithe3dbfe02013-06-30 10:40:20 +000011222 void VisitCallExpr(CallExpr *CE) {
11223 // C++11 [intro.execution]p15:
11224 // When calling a function [...], every value computation and side effect
11225 // associated with any argument expression, or with the postfix expression
11226 // designating the called function, is sequenced before execution of every
11227 // expression or statement in the body of the function [and thus before
11228 // the value computation of its result].
11229 SequencedSubexpression Sequenced(*this);
11230 Base::VisitCallExpr(CE);
11231
11232 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11233 }
11234
Richard Smithc406cb72013-01-17 01:17:56 +000011235 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011236 // This is a call, so all subexpressions are sequenced before the result.
11237 SequencedSubexpression Sequenced(*this);
11238
Richard Smithc406cb72013-01-17 01:17:56 +000011239 if (!CCE->isListInitialization())
11240 return VisitExpr(CCE);
11241
11242 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011243 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011244 SequenceTree::Seq Parent = Region;
11245 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11246 E = CCE->arg_end();
11247 I != E; ++I) {
11248 Region = Tree.allocate(Parent);
11249 Elts.push_back(Region);
11250 Visit(*I);
11251 }
11252
11253 // Forget that the initializers are sequenced.
11254 Region = Parent;
11255 for (unsigned I = 0; I < Elts.size(); ++I)
11256 Tree.merge(Elts[I]);
11257 }
11258
11259 void VisitInitListExpr(InitListExpr *ILE) {
11260 if (!SemaRef.getLangOpts().CPlusPlus11)
11261 return VisitExpr(ILE);
11262
11263 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011264 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011265 SequenceTree::Seq Parent = Region;
11266 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11267 Expr *E = ILE->getInit(I);
11268 if (!E) continue;
11269 Region = Tree.allocate(Parent);
11270 Elts.push_back(Region);
11271 Visit(E);
11272 }
11273
11274 // Forget that the initializers are sequenced.
11275 Region = Parent;
11276 for (unsigned I = 0; I < Elts.size(); ++I)
11277 Tree.merge(Elts[I]);
11278 }
11279};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011280
11281} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011282
11283void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011284 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011285 WorkList.push_back(E);
11286 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011287 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011288 SequenceChecker(*this, Item, WorkList);
11289 }
Richard Smithc406cb72013-01-17 01:17:56 +000011290}
11291
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011292void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11293 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011294 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011295 if (!E->isInstantiationDependent())
11296 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011297 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011298 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011299 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011300}
11301
John McCall1f425642010-11-11 03:21:53 +000011302void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11303 FieldDecl *BitField,
11304 Expr *Init) {
11305 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11306}
11307
David Majnemer61a5bbf2015-04-07 22:08:51 +000011308static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11309 SourceLocation Loc) {
11310 if (!PType->isVariablyModifiedType())
11311 return;
11312 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11313 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11314 return;
11315 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011316 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11317 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11318 return;
11319 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011320 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11321 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11322 return;
11323 }
11324
11325 const ArrayType *AT = S.Context.getAsArrayType(PType);
11326 if (!AT)
11327 return;
11328
11329 if (AT->getSizeModifier() != ArrayType::Star) {
11330 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11331 return;
11332 }
11333
11334 S.Diag(Loc, diag::err_array_star_in_function_definition);
11335}
11336
Mike Stump0c2ec772010-01-21 03:59:47 +000011337/// CheckParmsForFunctionDef - Check that the parameters of the given
11338/// function are appropriate for the definition of a function. This
11339/// takes care of any checks that cannot be performed on the
11340/// declaration itself, e.g., that the types of each of the function
11341/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011342bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011343 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011344 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011345 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011346 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11347 // function declarator that is part of a function definition of
11348 // that function shall not have incomplete type.
11349 //
11350 // This is also C++ [dcl.fct]p6.
11351 if (!Param->isInvalidDecl() &&
11352 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011353 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011354 Param->setInvalidDecl();
11355 HasInvalidParm = true;
11356 }
11357
11358 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11359 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011360 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011361 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011362 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011363 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011364 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011365
11366 // C99 6.7.5.3p12:
11367 // If the function declarator is not part of a definition of that
11368 // function, parameters may have incomplete type and may use the [*]
11369 // notation in their sequences of declarator specifiers to specify
11370 // variable length array types.
11371 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011372 // FIXME: This diagnostic should point the '[*]' if source-location
11373 // information is added for it.
11374 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011375
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011376 // If the parameter is a c++ class type and it has to be destructed in the
11377 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011378 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011379 if (!Param->isInvalidDecl()) {
11380 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11381 if (!ClassDecl->isInvalidDecl() &&
11382 !ClassDecl->hasIrrelevantDestructor() &&
11383 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011384 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011385 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11386 MarkFunctionReferenced(Param->getLocation(), Destructor);
11387 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011388 }
11389 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011390 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011391
11392 // Parameters with the pass_object_size attribute only need to be marked
11393 // constant at function definitions. Because we lack information about
11394 // whether we're on a declaration or definition when we're instantiating the
11395 // attribute, we need to check for constness here.
11396 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11397 if (!Param->getType().isConstQualified())
11398 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11399 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011400 }
11401
11402 return HasInvalidParm;
11403}
John McCall2b5c1b22010-08-12 21:44:57 +000011404
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011405/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11406/// or MemberExpr.
11407static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11408 ASTContext &Context) {
11409 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11410 return Context.getDeclAlign(DRE->getDecl());
11411
11412 if (const auto *ME = dyn_cast<MemberExpr>(E))
11413 return Context.getDeclAlign(ME->getMemberDecl());
11414
11415 return TypeAlign;
11416}
11417
John McCall2b5c1b22010-08-12 21:44:57 +000011418/// CheckCastAlign - Implements -Wcast-align, which warns when a
11419/// pointer cast increases the alignment requirements.
11420void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11421 // This is actually a lot of work to potentially be doing on every
11422 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011423 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011424 return;
11425
11426 // Ignore dependent types.
11427 if (T->isDependentType() || Op->getType()->isDependentType())
11428 return;
11429
11430 // Require that the destination be a pointer type.
11431 const PointerType *DestPtr = T->getAs<PointerType>();
11432 if (!DestPtr) return;
11433
11434 // If the destination has alignment 1, we're done.
11435 QualType DestPointee = DestPtr->getPointeeType();
11436 if (DestPointee->isIncompleteType()) return;
11437 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11438 if (DestAlign.isOne()) return;
11439
11440 // Require that the source be a pointer type.
11441 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11442 if (!SrcPtr) return;
11443 QualType SrcPointee = SrcPtr->getPointeeType();
11444
11445 // Whitelist casts from cv void*. We already implicitly
11446 // whitelisted casts to cv void*, since they have alignment 1.
11447 // Also whitelist casts involving incomplete types, which implicitly
11448 // includes 'void'.
11449 if (SrcPointee->isIncompleteType()) return;
11450
11451 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011452
11453 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11454 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11455 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11456 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11457 if (UO->getOpcode() == UO_AddrOf)
11458 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11459 }
11460
John McCall2b5c1b22010-08-12 21:44:57 +000011461 if (SrcAlign >= DestAlign) return;
11462
11463 Diag(TRange.getBegin(), diag::warn_cast_align)
11464 << Op->getType() << T
11465 << static_cast<unsigned>(SrcAlign.getQuantity())
11466 << static_cast<unsigned>(DestAlign.getQuantity())
11467 << TRange << Op->getSourceRange();
11468}
11469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011470/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011471/// array member of a struct.
11472///
11473/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11474/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011475static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011476 const NamedDecl *ND) {
11477 if (Size != 1 || !ND) return false;
11478
11479 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11480 if (!FD) return false;
11481
11482 // Don't consider sizes resulting from macro expansions or template argument
11483 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011484
11485 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011486 while (TInfo) {
11487 TypeLoc TL = TInfo->getTypeLoc();
11488 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011489 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11490 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011491 TInfo = TDL->getTypeSourceInfo();
11492 continue;
11493 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011494 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11495 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011496 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11497 return false;
11498 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011499 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011500 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011501
11502 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011503 if (!RD) return false;
11504 if (RD->isUnion()) return false;
11505 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11506 if (!CRD->isStandardLayout()) return false;
11507 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011508
Benjamin Kramer8c543672011-08-06 03:04:42 +000011509 // See if this is the last field decl in the record.
11510 const Decl *D = FD;
11511 while ((D = D->getNextDeclInContext()))
11512 if (isa<FieldDecl>(D))
11513 return false;
11514 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011515}
11516
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011517void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011518 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011519 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011520 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011521 if (IndexExpr->isValueDependent())
11522 return;
11523
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011524 const Type *EffectiveType =
11525 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011526 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011527 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011528 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011529 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011530 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011531
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011532 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011533 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011534 return;
Richard Smith13f67182011-12-16 19:31:14 +000011535 if (IndexNegated)
11536 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011537
Craig Topperc3ec1492014-05-26 06:22:03 +000011538 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011539 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011540 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011541 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011542 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011543
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011544 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011545 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011546 if (!size.isStrictlyPositive())
11547 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011548
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011549 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011550 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011551 // Make sure we're comparing apples to apples when comparing index to size
11552 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11553 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011554 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011555 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011556 if (ptrarith_typesize != array_typesize) {
11557 // There's a cast to a different size type involved
11558 uint64_t ratio = array_typesize / ptrarith_typesize;
11559 // TODO: Be smarter about handling cases where array_typesize is not a
11560 // multiple of ptrarith_typesize
11561 if (ptrarith_typesize * ratio == array_typesize)
11562 size *= llvm::APInt(size.getBitWidth(), ratio);
11563 }
11564 }
11565
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011566 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011567 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011568 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011569 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011570
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011571 // For array subscripting the index must be less than size, but for pointer
11572 // arithmetic also allow the index (offset) to be equal to size since
11573 // computing the next address after the end of the array is legal and
11574 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011575 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011576 return;
11577
11578 // Also don't warn for arrays of size 1 which are members of some
11579 // structure. These are often used to approximate flexible arrays in C89
11580 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011581 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011582 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011583
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011584 // Suppress the warning if the subscript expression (as identified by the
11585 // ']' location) and the index expression are both from macro expansions
11586 // within a system header.
11587 if (ASE) {
11588 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11589 ASE->getRBracketLoc());
11590 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11591 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11592 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011593 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011594 return;
11595 }
11596 }
11597
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011598 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011599 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011600 DiagID = diag::warn_array_index_exceeds_bounds;
11601
11602 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11603 PDiag(DiagID) << index.toString(10, true)
11604 << size.toString(10, true)
11605 << (unsigned)size.getLimitedValue(~0U)
11606 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011607 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011608 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011609 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011610 DiagID = diag::warn_ptr_arith_precedes_bounds;
11611 if (index.isNegative()) index = -index;
11612 }
11613
11614 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11615 PDiag(DiagID) << index.toString(10, true)
11616 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011617 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011618
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011619 if (!ND) {
11620 // Try harder to find a NamedDecl to point at in the note.
11621 while (const ArraySubscriptExpr *ASE =
11622 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11623 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11624 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011625 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011626 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011627 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011628 }
11629
Chandler Carruth1af88f12011-02-17 21:10:52 +000011630 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011631 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11632 PDiag(diag::note_array_index_out_of_bounds)
11633 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011634}
11635
Ted Kremenekdf26df72011-03-01 18:41:00 +000011636void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011637 int AllowOnePastEnd = 0;
11638 while (expr) {
11639 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011640 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011641 case Stmt::ArraySubscriptExprClass: {
11642 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011643 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011644 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011645 expr = ASE->getBase();
11646 break;
11647 }
11648 case Stmt::MemberExprClass: {
11649 expr = cast<MemberExpr>(expr)->getBase();
11650 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011651 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011652 case Stmt::OMPArraySectionExprClass: {
11653 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11654 if (ASE->getLowerBound())
11655 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11656 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11657 return;
11658 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011659 case Stmt::UnaryOperatorClass: {
11660 // Only unwrap the * and & unary operators
11661 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11662 expr = UO->getSubExpr();
11663 switch (UO->getOpcode()) {
11664 case UO_AddrOf:
11665 AllowOnePastEnd++;
11666 break;
11667 case UO_Deref:
11668 AllowOnePastEnd--;
11669 break;
11670 default:
11671 return;
11672 }
11673 break;
11674 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011675 case Stmt::ConditionalOperatorClass: {
11676 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11677 if (const Expr *lhs = cond->getLHS())
11678 CheckArrayAccess(lhs);
11679 if (const Expr *rhs = cond->getRHS())
11680 CheckArrayAccess(rhs);
11681 return;
11682 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011683 case Stmt::CXXOperatorCallExprClass: {
11684 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11685 for (const auto *Arg : OCE->arguments())
11686 CheckArrayAccess(Arg);
11687 return;
11688 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011689 default:
11690 return;
11691 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011692 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011693}
John McCall31168b02011-06-15 23:02:42 +000011694
11695//===--- CHECK: Objective-C retain cycles ----------------------------------//
11696
11697namespace {
John McCall31168b02011-06-15 23:02:42 +000011698
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011699struct RetainCycleOwner {
11700 VarDecl *Variable = nullptr;
11701 SourceRange Range;
11702 SourceLocation Loc;
11703 bool Indirect = false;
11704
11705 RetainCycleOwner() = default;
11706
11707 void setLocsFrom(Expr *e) {
11708 Loc = e->getExprLoc();
11709 Range = e->getSourceRange();
11710 }
11711};
11712
11713} // namespace
John McCall31168b02011-06-15 23:02:42 +000011714
11715/// Consider whether capturing the given variable can possibly lead to
11716/// a retain cycle.
11717static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011718 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011719 // lifetime. In MRR, it's captured strongly if the variable is
11720 // __block and has an appropriate type.
11721 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11722 return false;
11723
11724 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011725 if (ref)
11726 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011727 return true;
11728}
11729
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011730static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011731 while (true) {
11732 e = e->IgnoreParens();
11733 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11734 switch (cast->getCastKind()) {
11735 case CK_BitCast:
11736 case CK_LValueBitCast:
11737 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011738 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011739 e = cast->getSubExpr();
11740 continue;
11741
John McCall31168b02011-06-15 23:02:42 +000011742 default:
11743 return false;
11744 }
11745 }
11746
11747 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11748 ObjCIvarDecl *ivar = ref->getDecl();
11749 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11750 return false;
11751
11752 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011753 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011754 return false;
11755
11756 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11757 owner.Indirect = true;
11758 return true;
11759 }
11760
11761 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11762 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11763 if (!var) return false;
11764 return considerVariable(var, ref, owner);
11765 }
11766
John McCall31168b02011-06-15 23:02:42 +000011767 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11768 if (member->isArrow()) return false;
11769
11770 // Don't count this as an indirect ownership.
11771 e = member->getBase();
11772 continue;
11773 }
11774
John McCallfe96e0b2011-11-06 09:01:30 +000011775 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11776 // Only pay attention to pseudo-objects on property references.
11777 ObjCPropertyRefExpr *pre
11778 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11779 ->IgnoreParens());
11780 if (!pre) return false;
11781 if (pre->isImplicitProperty()) return false;
11782 ObjCPropertyDecl *property = pre->getExplicitProperty();
11783 if (!property->isRetaining() &&
11784 !(property->getPropertyIvarDecl() &&
11785 property->getPropertyIvarDecl()->getType()
11786 .getObjCLifetime() == Qualifiers::OCL_Strong))
11787 return false;
11788
11789 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011790 if (pre->isSuperReceiver()) {
11791 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11792 if (!owner.Variable)
11793 return false;
11794 owner.Loc = pre->getLocation();
11795 owner.Range = pre->getSourceRange();
11796 return true;
11797 }
John McCallfe96e0b2011-11-06 09:01:30 +000011798 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11799 ->getSourceExpr());
11800 continue;
11801 }
11802
John McCall31168b02011-06-15 23:02:42 +000011803 // Array ivars?
11804
11805 return false;
11806 }
11807}
11808
11809namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011810
John McCall31168b02011-06-15 23:02:42 +000011811 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011812 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011813 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011814 Expr *Capturer = nullptr;
11815 bool VarWillBeReased = false;
11816
11817 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11818 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11819 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011820
11821 void VisitDeclRefExpr(DeclRefExpr *ref) {
11822 if (ref->getDecl() == Variable && !Capturer)
11823 Capturer = ref;
11824 }
11825
John McCall31168b02011-06-15 23:02:42 +000011826 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11827 if (Capturer) return;
11828 Visit(ref->getBase());
11829 if (Capturer && ref->isFreeIvar())
11830 Capturer = ref;
11831 }
11832
11833 void VisitBlockExpr(BlockExpr *block) {
11834 // Look inside nested blocks
11835 if (block->getBlockDecl()->capturesVariable(Variable))
11836 Visit(block->getBlockDecl()->getBody());
11837 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011838
11839 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11840 if (Capturer) return;
11841 if (OVE->getSourceExpr())
11842 Visit(OVE->getSourceExpr());
11843 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011844
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011845 void VisitBinaryOperator(BinaryOperator *BinOp) {
11846 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11847 return;
11848 Expr *LHS = BinOp->getLHS();
11849 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11850 if (DRE->getDecl() != Variable)
11851 return;
11852 if (Expr *RHS = BinOp->getRHS()) {
11853 RHS = RHS->IgnoreParenCasts();
11854 llvm::APSInt Value;
11855 VarWillBeReased =
11856 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11857 }
11858 }
11859 }
John McCall31168b02011-06-15 23:02:42 +000011860 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011861
11862} // namespace
John McCall31168b02011-06-15 23:02:42 +000011863
11864/// Check whether the given argument is a block which captures a
11865/// variable.
11866static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11867 assert(owner.Variable && owner.Loc.isValid());
11868
11869 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011870
11871 // Look through [^{...} copy] and Block_copy(^{...}).
11872 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11873 Selector Cmd = ME->getSelector();
11874 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11875 e = ME->getInstanceReceiver();
11876 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011877 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011878 e = e->IgnoreParenCasts();
11879 }
11880 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11881 if (CE->getNumArgs() == 1) {
11882 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011883 if (Fn) {
11884 const IdentifierInfo *FnI = Fn->getIdentifier();
11885 if (FnI && FnI->isStr("_Block_copy")) {
11886 e = CE->getArg(0)->IgnoreParenCasts();
11887 }
11888 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011889 }
11890 }
11891
John McCall31168b02011-06-15 23:02:42 +000011892 BlockExpr *block = dyn_cast<BlockExpr>(e);
11893 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011894 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011895
11896 FindCaptureVisitor visitor(S.Context, owner.Variable);
11897 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011898 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011899}
11900
11901static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11902 RetainCycleOwner &owner) {
11903 assert(capturer);
11904 assert(owner.Variable && owner.Loc.isValid());
11905
11906 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11907 << owner.Variable << capturer->getSourceRange();
11908 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11909 << owner.Indirect << owner.Range;
11910}
11911
11912/// Check for a keyword selector that starts with the word 'add' or
11913/// 'set'.
11914static bool isSetterLikeSelector(Selector sel) {
11915 if (sel.isUnarySelector()) return false;
11916
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011917 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011918 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011919 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011920 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011921 else if (str.startswith("add")) {
11922 // Specially whitelist 'addOperationWithBlock:'.
11923 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11924 return false;
11925 str = str.substr(3);
11926 }
John McCall31168b02011-06-15 23:02:42 +000011927 else
11928 return false;
11929
11930 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011931 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011932}
11933
Benjamin Kramer3a743452015-03-09 15:03:32 +000011934static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11935 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011936 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11937 Message->getReceiverInterface(),
11938 NSAPI::ClassId_NSMutableArray);
11939 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011940 return None;
11941 }
11942
11943 Selector Sel = Message->getSelector();
11944
11945 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11946 S.NSAPIObj->getNSArrayMethodKind(Sel);
11947 if (!MKOpt) {
11948 return None;
11949 }
11950
11951 NSAPI::NSArrayMethodKind MK = *MKOpt;
11952
11953 switch (MK) {
11954 case NSAPI::NSMutableArr_addObject:
11955 case NSAPI::NSMutableArr_insertObjectAtIndex:
11956 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11957 return 0;
11958 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11959 return 1;
11960
11961 default:
11962 return None;
11963 }
11964
11965 return None;
11966}
11967
11968static
11969Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11970 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011971 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11972 Message->getReceiverInterface(),
11973 NSAPI::ClassId_NSMutableDictionary);
11974 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011975 return None;
11976 }
11977
11978 Selector Sel = Message->getSelector();
11979
11980 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11981 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11982 if (!MKOpt) {
11983 return None;
11984 }
11985
11986 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11987
11988 switch (MK) {
11989 case NSAPI::NSMutableDict_setObjectForKey:
11990 case NSAPI::NSMutableDict_setValueForKey:
11991 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11992 return 0;
11993
11994 default:
11995 return None;
11996 }
11997
11998 return None;
11999}
12000
12001static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012002 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12003 Message->getReceiverInterface(),
12004 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012005
Alex Denisov5dfac812015-08-06 04:51:14 +000012006 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12007 Message->getReceiverInterface(),
12008 NSAPI::ClassId_NSMutableOrderedSet);
12009 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012010 return None;
12011 }
12012
12013 Selector Sel = Message->getSelector();
12014
12015 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12016 if (!MKOpt) {
12017 return None;
12018 }
12019
12020 NSAPI::NSSetMethodKind MK = *MKOpt;
12021
12022 switch (MK) {
12023 case NSAPI::NSMutableSet_addObject:
12024 case NSAPI::NSOrderedSet_setObjectAtIndex:
12025 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12026 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12027 return 0;
12028 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12029 return 1;
12030 }
12031
12032 return None;
12033}
12034
12035void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12036 if (!Message->isInstanceMessage()) {
12037 return;
12038 }
12039
12040 Optional<int> ArgOpt;
12041
12042 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12043 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12044 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12045 return;
12046 }
12047
12048 int ArgIndex = *ArgOpt;
12049
Alex Denisove1d882c2015-03-04 17:55:52 +000012050 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12051 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12052 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12053 }
12054
Alex Denisov5dfac812015-08-06 04:51:14 +000012055 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012056 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012057 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012058 Diag(Message->getSourceRange().getBegin(),
12059 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012060 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012061 }
12062 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012063 } else {
12064 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12065
12066 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12067 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12068 }
12069
12070 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12071 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12072 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12073 ValueDecl *Decl = ReceiverRE->getDecl();
12074 Diag(Message->getSourceRange().getBegin(),
12075 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012076 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012077 if (!ArgRE->isObjCSelfExpr()) {
12078 Diag(Decl->getLocation(),
12079 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012080 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012081 }
12082 }
12083 }
12084 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12085 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12086 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12087 ObjCIvarDecl *Decl = IvarRE->getDecl();
12088 Diag(Message->getSourceRange().getBegin(),
12089 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012090 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012091 Diag(Decl->getLocation(),
12092 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012093 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012094 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012095 }
12096 }
12097 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012098}
12099
John McCall31168b02011-06-15 23:02:42 +000012100/// Check a message send to see if it's likely to cause a retain cycle.
12101void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12102 // Only check instance methods whose selector looks like a setter.
12103 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12104 return;
12105
12106 // Try to find a variable that the receiver is strongly owned by.
12107 RetainCycleOwner owner;
12108 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012109 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012110 return;
12111 } else {
12112 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12113 owner.Variable = getCurMethodDecl()->getSelfDecl();
12114 owner.Loc = msg->getSuperLoc();
12115 owner.Range = msg->getSuperLoc();
12116 }
12117
12118 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012119 const ObjCMethodDecl *MD = msg->getMethodDecl();
12120 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12121 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12122 // noescape blocks should not be retained by the method.
12123 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12124 continue;
John McCall31168b02011-06-15 23:02:42 +000012125 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012126 }
12127 }
John McCall31168b02011-06-15 23:02:42 +000012128}
12129
12130/// Check a property assign to see if it's likely to cause a retain cycle.
12131void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12132 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012133 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012134 return;
12135
12136 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12137 diagnoseRetainCycle(*this, capturer, owner);
12138}
12139
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012140void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12141 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012142 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012143 return;
12144
12145 // Because we don't have an expression for the variable, we have to set the
12146 // location explicitly here.
12147 Owner.Loc = Var->getLocation();
12148 Owner.Range = Var->getSourceRange();
12149
12150 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12151 diagnoseRetainCycle(*this, Capturer, Owner);
12152}
12153
Ted Kremenek9304da92012-12-21 08:04:28 +000012154static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12155 Expr *RHS, bool isProperty) {
12156 // Check if RHS is an Objective-C object literal, which also can get
12157 // immediately zapped in a weak reference. Note that we explicitly
12158 // allow ObjCStringLiterals, since those are designed to never really die.
12159 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012160
Ted Kremenek64873352012-12-21 22:46:35 +000012161 // This enum needs to match with the 'select' in
12162 // warn_objc_arc_literal_assign (off-by-1).
12163 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12164 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12165 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012166
12167 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012168 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012169 << (isProperty ? 0 : 1)
12170 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012171
12172 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012173}
12174
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012175static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12176 Qualifiers::ObjCLifetime LT,
12177 Expr *RHS, bool isProperty) {
12178 // Strip off any implicit cast added to get to the one ARC-specific.
12179 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12180 if (cast->getCastKind() == CK_ARCConsumeObject) {
12181 S.Diag(Loc, diag::warn_arc_retained_assign)
12182 << (LT == Qualifiers::OCL_ExplicitNone)
12183 << (isProperty ? 0 : 1)
12184 << RHS->getSourceRange();
12185 return true;
12186 }
12187 RHS = cast->getSubExpr();
12188 }
12189
12190 if (LT == Qualifiers::OCL_Weak &&
12191 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12192 return true;
12193
12194 return false;
12195}
12196
Ted Kremenekb36234d2012-12-21 08:04:20 +000012197bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12198 QualType LHS, Expr *RHS) {
12199 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12200
12201 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12202 return false;
12203
12204 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12205 return true;
12206
12207 return false;
12208}
12209
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012210void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12211 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012212 QualType LHSType;
12213 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012214 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012215 ObjCPropertyRefExpr *PRE
12216 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12217 if (PRE && !PRE->isImplicitProperty()) {
12218 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12219 if (PD)
12220 LHSType = PD->getType();
12221 }
12222
12223 if (LHSType.isNull())
12224 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012225
12226 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12227
12228 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012229 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012230 getCurFunction()->markSafeWeakUse(LHS);
12231 }
12232
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012233 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12234 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012235
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012236 // FIXME. Check for other life times.
12237 if (LT != Qualifiers::OCL_None)
12238 return;
12239
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012240 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012241 if (PRE->isImplicitProperty())
12242 return;
12243 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12244 if (!PD)
12245 return;
12246
Bill Wendling44426052012-12-20 19:22:21 +000012247 unsigned Attributes = PD->getPropertyAttributes();
12248 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012249 // when 'assign' attribute was not explicitly specified
12250 // by user, ignore it and rely on property type itself
12251 // for lifetime info.
12252 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12253 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12254 LHSType->isObjCRetainableType())
12255 return;
12256
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012257 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012258 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012259 Diag(Loc, diag::warn_arc_retained_property_assign)
12260 << RHS->getSourceRange();
12261 return;
12262 }
12263 RHS = cast->getSubExpr();
12264 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012265 }
Bill Wendling44426052012-12-20 19:22:21 +000012266 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012267 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12268 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012269 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012270 }
12271}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012272
12273//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12274
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012275static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12276 SourceLocation StmtLoc,
12277 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012278 // Do not warn if the body is a macro that expands to nothing, e.g:
12279 //
12280 // #define CALL(x)
12281 // if (condition)
12282 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012283 if (Body->hasLeadingEmptyMacro())
12284 return false;
12285
12286 // Get line numbers of statement and body.
12287 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012288 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012289 &StmtLineInvalid);
12290 if (StmtLineInvalid)
12291 return false;
12292
12293 bool BodyLineInvalid;
12294 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12295 &BodyLineInvalid);
12296 if (BodyLineInvalid)
12297 return false;
12298
12299 // Warn if null statement and body are on the same line.
12300 if (StmtLine != BodyLine)
12301 return false;
12302
12303 return true;
12304}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012305
12306void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12307 const Stmt *Body,
12308 unsigned DiagID) {
12309 // Since this is a syntactic check, don't emit diagnostic for template
12310 // instantiations, this just adds noise.
12311 if (CurrentInstantiationScope)
12312 return;
12313
12314 // The body should be a null statement.
12315 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12316 if (!NBody)
12317 return;
12318
12319 // Do the usual checks.
12320 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12321 return;
12322
12323 Diag(NBody->getSemiLoc(), DiagID);
12324 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12325}
12326
12327void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12328 const Stmt *PossibleBody) {
12329 assert(!CurrentInstantiationScope); // Ensured by caller
12330
12331 SourceLocation StmtLoc;
12332 const Stmt *Body;
12333 unsigned DiagID;
12334 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12335 StmtLoc = FS->getRParenLoc();
12336 Body = FS->getBody();
12337 DiagID = diag::warn_empty_for_body;
12338 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12339 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12340 Body = WS->getBody();
12341 DiagID = diag::warn_empty_while_body;
12342 } else
12343 return; // Neither `for' nor `while'.
12344
12345 // The body should be a null statement.
12346 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12347 if (!NBody)
12348 return;
12349
12350 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012351 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012352 return;
12353
12354 // Do the usual checks.
12355 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12356 return;
12357
12358 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12359 // noise level low, emit diagnostics only if for/while is followed by a
12360 // CompoundStmt, e.g.:
12361 // for (int i = 0; i < n; i++);
12362 // {
12363 // a(i);
12364 // }
12365 // or if for/while is followed by a statement with more indentation
12366 // than for/while itself:
12367 // for (int i = 0; i < n; i++);
12368 // a(i);
12369 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12370 if (!ProbableTypo) {
12371 bool BodyColInvalid;
12372 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12373 PossibleBody->getLocStart(),
12374 &BodyColInvalid);
12375 if (BodyColInvalid)
12376 return;
12377
12378 bool StmtColInvalid;
12379 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12380 S->getLocStart(),
12381 &StmtColInvalid);
12382 if (StmtColInvalid)
12383 return;
12384
12385 if (BodyCol > StmtCol)
12386 ProbableTypo = true;
12387 }
12388
12389 if (ProbableTypo) {
12390 Diag(NBody->getSemiLoc(), DiagID);
12391 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12392 }
12393}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012394
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012395//===--- CHECK: Warn on self move with std::move. -------------------------===//
12396
12397/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12398void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12399 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012400 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12401 return;
12402
Richard Smith51ec0cf2017-02-21 01:17:38 +000012403 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012404 return;
12405
12406 // Strip parens and casts away.
12407 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12408 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12409
12410 // Check for a call expression
12411 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12412 if (!CE || CE->getNumArgs() != 1)
12413 return;
12414
12415 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012416 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012417 return;
12418
12419 // Get argument from std::move
12420 RHSExpr = CE->getArg(0);
12421
12422 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12423 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12424
12425 // Two DeclRefExpr's, check that the decls are the same.
12426 if (LHSDeclRef && RHSDeclRef) {
12427 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12428 return;
12429 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12430 RHSDeclRef->getDecl()->getCanonicalDecl())
12431 return;
12432
12433 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12434 << LHSExpr->getSourceRange()
12435 << RHSExpr->getSourceRange();
12436 return;
12437 }
12438
12439 // Member variables require a different approach to check for self moves.
12440 // MemberExpr's are the same if every nested MemberExpr refers to the same
12441 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12442 // the base Expr's are CXXThisExpr's.
12443 const Expr *LHSBase = LHSExpr;
12444 const Expr *RHSBase = RHSExpr;
12445 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12446 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12447 if (!LHSME || !RHSME)
12448 return;
12449
12450 while (LHSME && RHSME) {
12451 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12452 RHSME->getMemberDecl()->getCanonicalDecl())
12453 return;
12454
12455 LHSBase = LHSME->getBase();
12456 RHSBase = RHSME->getBase();
12457 LHSME = dyn_cast<MemberExpr>(LHSBase);
12458 RHSME = dyn_cast<MemberExpr>(RHSBase);
12459 }
12460
12461 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12462 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12463 if (LHSDeclRef && RHSDeclRef) {
12464 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12465 return;
12466 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12467 RHSDeclRef->getDecl()->getCanonicalDecl())
12468 return;
12469
12470 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12471 << LHSExpr->getSourceRange()
12472 << RHSExpr->getSourceRange();
12473 return;
12474 }
12475
12476 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12477 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12478 << LHSExpr->getSourceRange()
12479 << RHSExpr->getSourceRange();
12480}
12481
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012482//===--- Layout compatibility ----------------------------------------------//
12483
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012484static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012486/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012487static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012488 // C++11 [dcl.enum] p8:
12489 // Two enumeration types are layout-compatible if they have the same
12490 // underlying type.
12491 return ED1->isComplete() && ED2->isComplete() &&
12492 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12493}
12494
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012495/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012496static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12497 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012498 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12499 return false;
12500
12501 if (Field1->isBitField() != Field2->isBitField())
12502 return false;
12503
12504 if (Field1->isBitField()) {
12505 // Make sure that the bit-fields are the same length.
12506 unsigned Bits1 = Field1->getBitWidthValue(C);
12507 unsigned Bits2 = Field2->getBitWidthValue(C);
12508
12509 if (Bits1 != Bits2)
12510 return false;
12511 }
12512
12513 return true;
12514}
12515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012516/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012517/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012518static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12519 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012520 // If both records are C++ classes, check that base classes match.
12521 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12522 // If one of records is a CXXRecordDecl we are in C++ mode,
12523 // thus the other one is a CXXRecordDecl, too.
12524 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12525 // Check number of base classes.
12526 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12527 return false;
12528
12529 // Check the base classes.
12530 for (CXXRecordDecl::base_class_const_iterator
12531 Base1 = D1CXX->bases_begin(),
12532 BaseEnd1 = D1CXX->bases_end(),
12533 Base2 = D2CXX->bases_begin();
12534 Base1 != BaseEnd1;
12535 ++Base1, ++Base2) {
12536 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12537 return false;
12538 }
12539 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12540 // If only RD2 is a C++ class, it should have zero base classes.
12541 if (D2CXX->getNumBases() > 0)
12542 return false;
12543 }
12544
12545 // Check the fields.
12546 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12547 Field2End = RD2->field_end(),
12548 Field1 = RD1->field_begin(),
12549 Field1End = RD1->field_end();
12550 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12551 if (!isLayoutCompatible(C, *Field1, *Field2))
12552 return false;
12553 }
12554 if (Field1 != Field1End || Field2 != Field2End)
12555 return false;
12556
12557 return true;
12558}
12559
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012560/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012561/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012562static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12563 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012564 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012565 for (auto *Field2 : RD2->fields())
12566 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012567
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012568 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012569 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12570 I = UnmatchedFields.begin(),
12571 E = UnmatchedFields.end();
12572
12573 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012574 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012575 bool Result = UnmatchedFields.erase(*I);
12576 (void) Result;
12577 assert(Result);
12578 break;
12579 }
12580 }
12581 if (I == E)
12582 return false;
12583 }
12584
12585 return UnmatchedFields.empty();
12586}
12587
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012588static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12589 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012590 if (RD1->isUnion() != RD2->isUnion())
12591 return false;
12592
12593 if (RD1->isUnion())
12594 return isLayoutCompatibleUnion(C, RD1, RD2);
12595 else
12596 return isLayoutCompatibleStruct(C, RD1, RD2);
12597}
12598
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012599/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012600static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012601 if (T1.isNull() || T2.isNull())
12602 return false;
12603
12604 // C++11 [basic.types] p11:
12605 // If two types T1 and T2 are the same type, then T1 and T2 are
12606 // layout-compatible types.
12607 if (C.hasSameType(T1, T2))
12608 return true;
12609
12610 T1 = T1.getCanonicalType().getUnqualifiedType();
12611 T2 = T2.getCanonicalType().getUnqualifiedType();
12612
12613 const Type::TypeClass TC1 = T1->getTypeClass();
12614 const Type::TypeClass TC2 = T2->getTypeClass();
12615
12616 if (TC1 != TC2)
12617 return false;
12618
12619 if (TC1 == Type::Enum) {
12620 return isLayoutCompatible(C,
12621 cast<EnumType>(T1)->getDecl(),
12622 cast<EnumType>(T2)->getDecl());
12623 } else if (TC1 == Type::Record) {
12624 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12625 return false;
12626
12627 return isLayoutCompatible(C,
12628 cast<RecordType>(T1)->getDecl(),
12629 cast<RecordType>(T2)->getDecl());
12630 }
12631
12632 return false;
12633}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012634
12635//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12636
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012637/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012638///
12639/// \param TypeExpr Type tag expression, as it appears in user's code.
12640///
12641/// \param VD Declaration of an identifier that appears in a type tag.
12642///
12643/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012644static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12645 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012646 while(true) {
12647 if (!TypeExpr)
12648 return false;
12649
12650 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12651
12652 switch (TypeExpr->getStmtClass()) {
12653 case Stmt::UnaryOperatorClass: {
12654 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12655 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12656 TypeExpr = UO->getSubExpr();
12657 continue;
12658 }
12659 return false;
12660 }
12661
12662 case Stmt::DeclRefExprClass: {
12663 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12664 *VD = DRE->getDecl();
12665 return true;
12666 }
12667
12668 case Stmt::IntegerLiteralClass: {
12669 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12670 llvm::APInt MagicValueAPInt = IL->getValue();
12671 if (MagicValueAPInt.getActiveBits() <= 64) {
12672 *MagicValue = MagicValueAPInt.getZExtValue();
12673 return true;
12674 } else
12675 return false;
12676 }
12677
12678 case Stmt::BinaryConditionalOperatorClass:
12679 case Stmt::ConditionalOperatorClass: {
12680 const AbstractConditionalOperator *ACO =
12681 cast<AbstractConditionalOperator>(TypeExpr);
12682 bool Result;
12683 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12684 if (Result)
12685 TypeExpr = ACO->getTrueExpr();
12686 else
12687 TypeExpr = ACO->getFalseExpr();
12688 continue;
12689 }
12690 return false;
12691 }
12692
12693 case Stmt::BinaryOperatorClass: {
12694 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12695 if (BO->getOpcode() == BO_Comma) {
12696 TypeExpr = BO->getRHS();
12697 continue;
12698 }
12699 return false;
12700 }
12701
12702 default:
12703 return false;
12704 }
12705 }
12706}
12707
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012708/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012709///
12710/// \param TypeExpr Expression that specifies a type tag.
12711///
12712/// \param MagicValues Registered magic values.
12713///
12714/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12715/// kind.
12716///
12717/// \param TypeInfo Information about the corresponding C type.
12718///
12719/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012720static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012721 const IdentifierInfo *ArgumentKind,
12722 const Expr *TypeExpr, const ASTContext &Ctx,
12723 const llvm::DenseMap<Sema::TypeTagMagicValue,
12724 Sema::TypeTagData> *MagicValues,
12725 bool &FoundWrongKind,
12726 Sema::TypeTagData &TypeInfo) {
12727 FoundWrongKind = false;
12728
12729 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012730 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012731
12732 uint64_t MagicValue;
12733
12734 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12735 return false;
12736
12737 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012738 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012739 if (I->getArgumentKind() != ArgumentKind) {
12740 FoundWrongKind = true;
12741 return false;
12742 }
12743 TypeInfo.Type = I->getMatchingCType();
12744 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12745 TypeInfo.MustBeNull = I->getMustBeNull();
12746 return true;
12747 }
12748 return false;
12749 }
12750
12751 if (!MagicValues)
12752 return false;
12753
12754 llvm::DenseMap<Sema::TypeTagMagicValue,
12755 Sema::TypeTagData>::const_iterator I =
12756 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12757 if (I == MagicValues->end())
12758 return false;
12759
12760 TypeInfo = I->second;
12761 return true;
12762}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012763
12764void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12765 uint64_t MagicValue, QualType Type,
12766 bool LayoutCompatible,
12767 bool MustBeNull) {
12768 if (!TypeTagForDatatypeMagicValues)
12769 TypeTagForDatatypeMagicValues.reset(
12770 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12771
12772 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12773 (*TypeTagForDatatypeMagicValues)[Magic] =
12774 TypeTagData(Type, LayoutCompatible, MustBeNull);
12775}
12776
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012777static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012778 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12779 if (!BT1)
12780 return false;
12781
12782 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12783 if (!BT2)
12784 return false;
12785
12786 BuiltinType::Kind T1Kind = BT1->getKind();
12787 BuiltinType::Kind T2Kind = BT2->getKind();
12788
12789 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12790 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12791 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12792 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12793}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012794
12795void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012796 const ArrayRef<const Expr *> ExprArgs,
12797 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012798 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12799 bool IsPointerAttr = Attr->getIsPointer();
12800
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012801 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012802 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12803 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012804 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012805 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012806 return;
12807 }
Joel E. Denny81508102018-03-13 14:51:22 +000012808 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012809 bool FoundWrongKind;
12810 TypeTagData TypeInfo;
12811 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12812 TypeTagForDatatypeMagicValues.get(),
12813 FoundWrongKind, TypeInfo)) {
12814 if (FoundWrongKind)
12815 Diag(TypeTagExpr->getExprLoc(),
12816 diag::warn_type_tag_for_datatype_wrong_kind)
12817 << TypeTagExpr->getSourceRange();
12818 return;
12819 }
12820
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012821 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012822 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12823 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012824 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012825 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012826 return;
12827 }
Joel E. Denny81508102018-03-13 14:51:22 +000012828 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012829 if (IsPointerAttr) {
12830 // Skip implicit cast of pointer to `void *' (as a function argument).
12831 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012832 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012833 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012834 ArgumentExpr = ICE->getSubExpr();
12835 }
12836 QualType ArgumentType = ArgumentExpr->getType();
12837
12838 // Passing a `void*' pointer shouldn't trigger a warning.
12839 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12840 return;
12841
12842 if (TypeInfo.MustBeNull) {
12843 // Type tag with matching void type requires a null pointer.
12844 if (!ArgumentExpr->isNullPointerConstant(Context,
12845 Expr::NPC_ValueDependentIsNotNull)) {
12846 Diag(ArgumentExpr->getExprLoc(),
12847 diag::warn_type_safety_null_pointer_required)
12848 << ArgumentKind->getName()
12849 << ArgumentExpr->getSourceRange()
12850 << TypeTagExpr->getSourceRange();
12851 }
12852 return;
12853 }
12854
12855 QualType RequiredType = TypeInfo.Type;
12856 if (IsPointerAttr)
12857 RequiredType = Context.getPointerType(RequiredType);
12858
12859 bool mismatch = false;
12860 if (!TypeInfo.LayoutCompatible) {
12861 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12862
12863 // C++11 [basic.fundamental] p1:
12864 // Plain char, signed char, and unsigned char are three distinct types.
12865 //
12866 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12867 // char' depending on the current char signedness mode.
12868 if (mismatch)
12869 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12870 RequiredType->getPointeeType())) ||
12871 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12872 mismatch = false;
12873 } else
12874 if (IsPointerAttr)
12875 mismatch = !isLayoutCompatible(Context,
12876 ArgumentType->getPointeeType(),
12877 RequiredType->getPointeeType());
12878 else
12879 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12880
12881 if (mismatch)
12882 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012883 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012884 << TypeInfo.LayoutCompatible << RequiredType
12885 << ArgumentExpr->getSourceRange()
12886 << TypeTagExpr->getSourceRange();
12887}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012888
12889void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12890 CharUnits Alignment) {
12891 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12892}
12893
12894void Sema::DiagnoseMisalignedMembers() {
12895 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012896 const NamedDecl *ND = m.RD;
12897 if (ND->getName().empty()) {
12898 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12899 ND = TD;
12900 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012901 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012902 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012903 }
12904 MisalignedMembers.clear();
12905}
12906
12907void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012908 E = E->IgnoreParens();
12909 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012910 return;
12911 if (isa<UnaryOperator>(E) &&
12912 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12913 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12914 if (isa<MemberExpr>(Op)) {
12915 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12916 MisalignedMember(Op));
12917 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012918 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012919 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12920 Context.getTypeAlignInChars(
12921 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012922 MisalignedMembers.erase(MA);
12923 }
12924 }
12925}
12926
12927void Sema::RefersToMemberWithReducedAlignment(
12928 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012929 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12930 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012931 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012932 if (!ME)
12933 return;
12934
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012935 // No need to check expressions with an __unaligned-qualified type.
12936 if (E->getType().getQualifiers().hasUnaligned())
12937 return;
12938
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012939 // For a chain of MemberExpr like "a.b.c.d" this list
12940 // will keep FieldDecl's like [d, c, b].
12941 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12942 const MemberExpr *TopME = nullptr;
12943 bool AnyIsPacked = false;
12944 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012945 QualType BaseType = ME->getBase()->getType();
12946 if (ME->isArrow())
12947 BaseType = BaseType->getPointeeType();
12948 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012949 if (RD->isInvalidDecl())
12950 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012951
12952 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012953 auto *FD = dyn_cast<FieldDecl>(MD);
12954 // We do not care about non-data members.
12955 if (!FD || FD->isInvalidDecl())
12956 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012957
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012958 AnyIsPacked =
12959 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12960 ReverseMemberChain.push_back(FD);
12961
12962 TopME = ME;
12963 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12964 } while (ME);
12965 assert(TopME && "We did not compute a topmost MemberExpr!");
12966
12967 // Not the scope of this diagnostic.
12968 if (!AnyIsPacked)
12969 return;
12970
12971 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12972 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12973 // TODO: The innermost base of the member expression may be too complicated.
12974 // For now, just disregard these cases. This is left for future
12975 // improvement.
12976 if (!DRE && !isa<CXXThisExpr>(TopBase))
12977 return;
12978
12979 // Alignment expected by the whole expression.
12980 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12981
12982 // No need to do anything else with this case.
12983 if (ExpectedAlignment.isOne())
12984 return;
12985
12986 // Synthesize offset of the whole access.
12987 CharUnits Offset;
12988 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12989 I++) {
12990 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12991 }
12992
12993 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12994 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12995 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12996
12997 // The base expression of the innermost MemberExpr may give
12998 // stronger guarantees than the class containing the member.
12999 if (DRE && !TopME->isArrow()) {
13000 const ValueDecl *VD = DRE->getDecl();
13001 if (!VD->getType()->isReferenceType())
13002 CompleteObjectAlignment =
13003 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13004 }
13005
13006 // Check if the synthesized offset fulfills the alignment.
13007 if (Offset % ExpectedAlignment != 0 ||
13008 // It may fulfill the offset it but the effective alignment may still be
13009 // lower than the expected expression alignment.
13010 CompleteObjectAlignment < ExpectedAlignment) {
13011 // If this happens, we want to determine a sensible culprit of this.
13012 // Intuitively, watching the chain of member expressions from right to
13013 // left, we start with the required alignment (as required by the field
13014 // type) but some packed attribute in that chain has reduced the alignment.
13015 // It may happen that another packed structure increases it again. But if
13016 // we are here such increase has not been enough. So pointing the first
13017 // FieldDecl that either is packed or else its RecordDecl is,
13018 // seems reasonable.
13019 FieldDecl *FD = nullptr;
13020 CharUnits Alignment;
13021 for (FieldDecl *FDI : ReverseMemberChain) {
13022 if (FDI->hasAttr<PackedAttr>() ||
13023 FDI->getParent()->hasAttr<PackedAttr>()) {
13024 FD = FDI;
13025 Alignment = std::min(
13026 Context.getTypeAlignInChars(FD->getType()),
13027 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13028 break;
13029 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013030 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013031 assert(FD && "We did not find a packed FieldDecl!");
13032 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013033 }
13034}
13035
13036void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13037 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013038
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013039 RefersToMemberWithReducedAlignment(
13040 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13041 _2, _3, _4));
13042}