blob: 9de512c70086d23e1d18e020f58f9f7422c3f27b [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) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000200 ExprResult Arg = TheCall->getArg(I);
201 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000202 if (!Ty->isIntegerType()) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000203 S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int)
204 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000205 return true;
206 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000207 InitializedEntity Entity = InitializedEntity::InitializeParameter(
208 S.getASTContext(), Ty, /*consume*/ false);
209 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
210 if (Arg.isInvalid())
211 return true;
212 TheCall->setArg(I, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000213 }
214
215 // Third argument should be a pointer to a non-const integer.
216 // IRGen correctly handles volatile, restrict, and address spaces, and
217 // the other qualifiers aren't possible.
218 {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000219 ExprResult Arg = TheCall->getArg(2);
220 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000221 const auto *PtrTy = Ty->getAs<PointerType>();
222 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
223 !PtrTy->getPointeeType().isConstQualified())) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000224 S.Diag(Arg.get()->getLocStart(),
225 diag::err_overflow_builtin_must_be_ptr_int)
226 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000227 return true;
228 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000229 InitializedEntity Entity = InitializedEntity::InitializeParameter(
230 S.getASTContext(), Ty, /*consume*/ false);
231 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
232 if (Arg.isInvalid())
233 return true;
234 TheCall->setArg(2, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000235 }
John McCall03107a42015-10-29 20:48:01 +0000236 return false;
237}
238
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000239static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Nico Weberade321e2018-04-10 18:53:28 +0000240 CallExpr *TheCall, unsigned SizeIdx,
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000241 unsigned DstSizeIdx) {
242 if (TheCall->getNumArgs() <= SizeIdx ||
243 TheCall->getNumArgs() <= DstSizeIdx)
244 return;
245
246 const Expr *SizeArg = TheCall->getArg(SizeIdx);
247 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
248
249 llvm::APSInt Size, DstSize;
250
251 // find out if both sizes are known at compile time
252 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
253 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
254 return;
255
256 if (Size.ule(DstSize))
257 return;
258
259 // confirmed overflow so generate the diagnostic.
260 IdentifierInfo *FnName = FDecl->getIdentifier();
261 SourceLocation SL = TheCall->getLocStart();
262 SourceRange SR = TheCall->getSourceRange();
263
264 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
265}
266
Peter Collingbournef7706832014-12-12 23:41:25 +0000267static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
268 if (checkArgCount(S, BuiltinCall, 2))
269 return true;
270
271 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
272 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
273 Expr *Call = BuiltinCall->getArg(0);
274 Expr *Chain = BuiltinCall->getArg(1);
275
276 if (Call->getStmtClass() != Stmt::CallExprClass) {
277 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
278 << Call->getSourceRange();
279 return true;
280 }
281
282 auto CE = cast<CallExpr>(Call);
283 if (CE->getCallee()->getType()->isBlockPointerType()) {
284 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
285 << Call->getSourceRange();
286 return true;
287 }
288
289 const Decl *TargetDecl = CE->getCalleeDecl();
290 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
291 if (FD->getBuiltinID()) {
292 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
293 << Call->getSourceRange();
294 return true;
295 }
296
297 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
298 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
299 << Call->getSourceRange();
300 return true;
301 }
302
303 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
304 if (ChainResult.isInvalid())
305 return true;
306 if (!ChainResult.get()->getType()->isPointerType()) {
307 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
308 << Chain->getSourceRange();
309 return true;
310 }
311
David Majnemerced8bdf2015-02-25 17:36:15 +0000312 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000313 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
314 QualType BuiltinTy = S.Context.getFunctionType(
315 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
316 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
317
318 Builtin =
319 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
320
321 BuiltinCall->setType(CE->getType());
322 BuiltinCall->setValueKind(CE->getValueKind());
323 BuiltinCall->setObjectKind(CE->getObjectKind());
324 BuiltinCall->setCallee(Builtin);
325 BuiltinCall->setArg(1, ChainResult.get());
326
327 return false;
328}
329
Reid Kleckner1d59f992015-01-22 01:36:17 +0000330static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
331 Scope::ScopeFlags NeededScopeFlags,
332 unsigned DiagID) {
333 // Scopes aren't available during instantiation. Fortunately, builtin
334 // functions cannot be template args so they cannot be formed through template
335 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000336 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000337 return false;
338
339 Scope *S = SemaRef.getCurScope();
340 while (S && !S->isSEHExceptScope())
341 S = S->getParent();
342 if (!S || !(S->getFlags() & NeededScopeFlags)) {
343 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
344 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
345 << DRE->getDecl()->getIdentifier();
346 return true;
347 }
348
349 return false;
350}
351
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000352static inline bool isBlockPointer(Expr *Arg) {
353 return Arg->getType()->isBlockPointerType();
354}
355
356/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
357/// void*, which is a requirement of device side enqueue.
358static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
359 const BlockPointerType *BPT =
360 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
361 ArrayRef<QualType> Params =
362 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
363 unsigned ArgCounter = 0;
364 bool IllegalParams = false;
365 // Iterate through the block parameters until either one is found that is not
366 // a local void*, or the block is valid.
367 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
368 I != E; ++I, ++ArgCounter) {
369 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
370 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
371 LangAS::opencl_local) {
372 // Get the location of the error. If a block literal has been passed
373 // (BlockExpr) then we can point straight to the offending argument,
374 // else we just point to the variable reference.
375 SourceLocation ErrorLoc;
376 if (isa<BlockExpr>(BlockArg)) {
377 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
378 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
379 } else if (isa<DeclRefExpr>(BlockArg)) {
380 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
381 }
382 S.Diag(ErrorLoc,
383 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
384 IllegalParams = true;
385 }
386 }
387
388 return IllegalParams;
389}
390
Joey Gouly84ae3362017-07-31 15:15:59 +0000391static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
392 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
393 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
394 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
395 return true;
396 }
397 return false;
398}
399
Joey Goulyfa76b492017-08-01 13:27:09 +0000400static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
401 if (checkArgCount(S, TheCall, 2))
402 return true;
403
404 if (checkOpenCLSubgroupExt(S, TheCall))
405 return true;
406
407 // First argument is an ndrange_t type.
408 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000409 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000410 S.Diag(NDRangeArg->getLocStart(),
411 diag::err_opencl_builtin_expected_type)
412 << TheCall->getDirectCallee() << "'ndrange_t'";
413 return true;
414 }
415
416 Expr *BlockArg = TheCall->getArg(1);
417 if (!isBlockPointer(BlockArg)) {
418 S.Diag(BlockArg->getLocStart(),
419 diag::err_opencl_builtin_expected_type)
420 << TheCall->getDirectCallee() << "block";
421 return true;
422 }
423 return checkOpenCLBlockArgs(S, BlockArg);
424}
425
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000426/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
427/// get_kernel_work_group_size
428/// and get_kernel_preferred_work_group_size_multiple builtin functions.
429static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
430 if (checkArgCount(S, TheCall, 1))
431 return true;
432
433 Expr *BlockArg = TheCall->getArg(0);
434 if (!isBlockPointer(BlockArg)) {
435 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000436 diag::err_opencl_builtin_expected_type)
437 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000438 return true;
439 }
440 return checkOpenCLBlockArgs(S, BlockArg);
441}
442
Simon Pilgrim2c518802017-03-30 14:13:19 +0000443/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000444static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
445 const QualType &IntType);
446
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000447static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000448 unsigned Start, unsigned End) {
449 bool IllegalParams = false;
450 for (unsigned I = Start; I <= End; ++I)
451 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
452 S.Context.getSizeType());
453 return IllegalParams;
454}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000455
456/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
457/// 'local void*' parameter of passed block.
458static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
459 Expr *BlockArg,
460 unsigned NumNonVarArgs) {
461 const BlockPointerType *BPT =
462 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
463 unsigned NumBlockParams =
464 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
465 unsigned TotalNumArgs = TheCall->getNumArgs();
466
467 // For each argument passed to the block, a corresponding uint needs to
468 // be passed to describe the size of the local memory.
469 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
470 S.Diag(TheCall->getLocStart(),
471 diag::err_opencl_enqueue_kernel_local_size_args);
472 return true;
473 }
474
475 // Check that the sizes of the local memory are specified by integers.
476 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
477 TotalNumArgs - 1);
478}
479
480/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
481/// overload formats specified in Table 6.13.17.1.
482/// int enqueue_kernel(queue_t queue,
483/// kernel_enqueue_flags_t flags,
484/// const ndrange_t ndrange,
485/// void (^block)(void))
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)(void))
493/// int enqueue_kernel(queue_t queue,
494/// kernel_enqueue_flags_t flags,
495/// const ndrange_t ndrange,
496/// void (^block)(local void*, ...),
497/// uint size0, ...)
498/// int enqueue_kernel(queue_t queue,
499/// kernel_enqueue_flags_t flags,
500/// const ndrange_t ndrange,
501/// uint num_events_in_wait_list,
502/// clk_event_t *event_wait_list,
503/// clk_event_t *event_ret,
504/// void (^block)(local void*, ...),
505/// uint size0, ...)
506static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
507 unsigned NumArgs = TheCall->getNumArgs();
508
509 if (NumArgs < 4) {
510 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
511 return true;
512 }
513
514 Expr *Arg0 = TheCall->getArg(0);
515 Expr *Arg1 = TheCall->getArg(1);
516 Expr *Arg2 = TheCall->getArg(2);
517 Expr *Arg3 = TheCall->getArg(3);
518
519 // First argument always needs to be a queue_t type.
520 if (!Arg0->getType()->isQueueT()) {
521 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000522 diag::err_opencl_builtin_expected_type)
523 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000524 return true;
525 }
526
527 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
528 if (!Arg1->getType()->isIntegerType()) {
529 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000530 diag::err_opencl_builtin_expected_type)
531 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000532 return true;
533 }
534
535 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000536 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000537 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000538 diag::err_opencl_builtin_expected_type)
539 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000540 return true;
541 }
542
543 // With four arguments, there is only one form that the function could be
544 // called in: no events and no variable arguments.
545 if (NumArgs == 4) {
546 // check that the last argument is the right block type.
547 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000548 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
549 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000550 return true;
551 }
552 // we have a block type, check the prototype
553 const BlockPointerType *BPT =
554 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
555 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
556 S.Diag(Arg3->getLocStart(),
557 diag::err_opencl_enqueue_kernel_blocks_no_args);
558 return true;
559 }
560 return false;
561 }
562 // we can have block + varargs.
563 if (isBlockPointer(Arg3))
564 return (checkOpenCLBlockArgs(S, Arg3) ||
565 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
566 // last two cases with either exactly 7 args or 7 args and varargs.
567 if (NumArgs >= 7) {
568 // check common block argument.
569 Expr *Arg6 = TheCall->getArg(6);
570 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000571 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
572 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000573 return true;
574 }
575 if (checkOpenCLBlockArgs(S, Arg6))
576 return true;
577
578 // Forth argument has to be any integer type.
579 if (!Arg3->getType()->isIntegerType()) {
580 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000581 diag::err_opencl_builtin_expected_type)
582 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000583 return true;
584 }
585 // check remaining common arguments.
586 Expr *Arg4 = TheCall->getArg(4);
587 Expr *Arg5 = TheCall->getArg(5);
588
Anastasia Stulova2b461202016-11-14 15:34:01 +0000589 // Fifth argument is always passed as a pointer to clk_event_t.
590 if (!Arg4->isNullPointerConstant(S.Context,
591 Expr::NPC_ValueDependentIsNotNull) &&
592 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000593 S.Diag(TheCall->getArg(4)->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
Anastasia Stulova2b461202016-11-14 15:34:01 +0000600 // Sixth argument is always passed as a pointer to clk_event_t.
601 if (!Arg5->isNullPointerConstant(S.Context,
602 Expr::NPC_ValueDependentIsNotNull) &&
603 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000604 Arg5->getType()->getPointeeType()->isClkEventT())) {
605 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000606 diag::err_opencl_builtin_expected_type)
607 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000608 << S.Context.getPointerType(S.Context.OCLClkEventTy);
609 return true;
610 }
611
612 if (NumArgs == 7)
613 return false;
614
615 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
616 }
617
618 // None of the specific case has been detected, give generic error
619 S.Diag(TheCall->getLocStart(),
620 diag::err_opencl_enqueue_kernel_incorrect_args);
621 return true;
622}
623
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000624/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000625static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000626 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000627}
628
629/// Returns true if pipe element type is different from the pointer.
630static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
631 const Expr *Arg0 = Call->getArg(0);
632 // First argument type should always be pipe.
633 if (!Arg0->getType()->isPipeType()) {
634 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000635 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000636 return true;
637 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000638 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000639 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
640 // Validates the access qualifier is compatible with the call.
641 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
642 // read_only and write_only, and assumed to be read_only if no qualifier is
643 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000644 switch (Call->getDirectCallee()->getBuiltinID()) {
645 case Builtin::BIread_pipe:
646 case Builtin::BIreserve_read_pipe:
647 case Builtin::BIcommit_read_pipe:
648 case Builtin::BIwork_group_reserve_read_pipe:
649 case Builtin::BIsub_group_reserve_read_pipe:
650 case Builtin::BIwork_group_commit_read_pipe:
651 case Builtin::BIsub_group_commit_read_pipe:
652 if (!(!AccessQual || AccessQual->isReadOnly())) {
653 S.Diag(Arg0->getLocStart(),
654 diag::err_opencl_builtin_pipe_invalid_access_modifier)
655 << "read_only" << Arg0->getSourceRange();
656 return true;
657 }
658 break;
659 case Builtin::BIwrite_pipe:
660 case Builtin::BIreserve_write_pipe:
661 case Builtin::BIcommit_write_pipe:
662 case Builtin::BIwork_group_reserve_write_pipe:
663 case Builtin::BIsub_group_reserve_write_pipe:
664 case Builtin::BIwork_group_commit_write_pipe:
665 case Builtin::BIsub_group_commit_write_pipe:
666 if (!(AccessQual && AccessQual->isWriteOnly())) {
667 S.Diag(Arg0->getLocStart(),
668 diag::err_opencl_builtin_pipe_invalid_access_modifier)
669 << "write_only" << Arg0->getSourceRange();
670 return true;
671 }
672 break;
673 default:
674 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000675 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000676 return false;
677}
678
679/// Returns true if pipe element type is different from the pointer.
680static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
681 const Expr *Arg0 = Call->getArg(0);
682 const Expr *ArgIdx = Call->getArg(Idx);
683 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000684 const QualType EltTy = PipeTy->getElementType();
685 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000686 // The Idx argument should be a pointer and the type of the pointer and
687 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000688 if (!ArgTy ||
689 !S.Context.hasSameType(
690 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000691 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000692 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000693 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000694 return true;
695 }
696 return false;
697}
698
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000699// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700// \param S Reference to the semantic analyzer.
701// \param Call A pointer to the builtin call.
702// \return True if a semantic error has been found, false otherwise.
703static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000704 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
705 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000706 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000707 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000708 if (checkOpenCLPipeArg(S, Call))
709 return true;
710 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000711 // read/write_pipe(pipe T, T*).
712 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000713 if (checkOpenCLPipePacketType(S, Call, 1))
714 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000715 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000716
717 case 4: {
718 if (checkOpenCLPipeArg(S, Call))
719 return true;
720 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000721 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
722 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000723 if (!Call->getArg(1)->getType()->isReserveIDT()) {
724 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000725 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000726 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000727 return true;
728 }
729
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000730 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000731 const Expr *Arg2 = Call->getArg(2);
732 if (!Arg2->getType()->isIntegerType() &&
733 !Arg2->getType()->isUnsignedIntegerType()) {
734 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000735 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000736 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000737 return true;
738 }
739
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000740 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000741 if (checkOpenCLPipePacketType(S, Call, 3))
742 return true;
743 } break;
744 default:
745 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000746 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000747 return true;
748 }
749
750 return false;
751}
752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000753// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000754// /_}reserve_{read/write}_pipe
755// \param S Reference to the semantic analyzer.
756// \param Call The call to the builtin function to be analyzed.
757// \return True if a semantic error was found, false otherwise.
758static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
759 if (checkArgCount(S, Call, 2))
760 return true;
761
762 if (checkOpenCLPipeArg(S, Call))
763 return true;
764
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000765 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000766 if (!Call->getArg(1)->getType()->isIntegerType() &&
767 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
768 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000769 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000770 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000771 return true;
772 }
773
Joey Gouly922ca232017-08-09 14:52:47 +0000774 // Since return type of reserve_read/write_pipe built-in function is
775 // reserve_id_t, which is not defined in the builtin def file , we used int
776 // as return type and need to override the return type of these functions.
777 Call->setType(S.Context.OCLReserveIDTy);
778
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000779 return false;
780}
781
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000782// Performs a semantic analysis on {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000783// /_}commit_{read/write}_pipe
784// \param S Reference to the semantic analyzer.
785// \param Call The call to the builtin function to be analyzed.
786// \return True if a semantic error was found, false otherwise.
787static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
788 if (checkArgCount(S, Call, 2))
789 return true;
790
791 if (checkOpenCLPipeArg(S, Call))
792 return true;
793
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000794 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000795 if (!Call->getArg(1)->getType()->isReserveIDT()) {
796 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000797 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000798 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000799 return true;
800 }
801
802 return false;
803}
804
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000805// Performs a semantic analysis on the call to built-in Pipe
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000806// Query Functions.
807// \param S Reference to the semantic analyzer.
808// \param Call The call to the builtin function to be analyzed.
809// \return True if a semantic error was found, false otherwise.
810static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
811 if (checkArgCount(S, Call, 1))
812 return true;
813
814 if (!Call->getArg(0)->getType()->isPipeType()) {
815 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000816 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000817 return true;
818 }
819
820 return false;
821}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000822
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000823// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
824// Performs semantic analysis for the to_global/local/private call.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000825// \param S Reference to the semantic analyzer.
826// \param BuiltinID ID of the builtin function.
827// \param Call A pointer to the builtin call.
828// \return True if a semantic error has been found, false otherwise.
829static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
830 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000831 if (Call->getNumArgs() != 1) {
832 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
833 << Call->getDirectCallee() << Call->getSourceRange();
834 return true;
835 }
836
837 auto RT = Call->getArg(0)->getType();
838 if (!RT->isPointerType() || RT->getPointeeType()
839 .getAddressSpace() == LangAS::opencl_constant) {
840 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
841 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
842 return true;
843 }
844
845 RT = RT->getPointeeType();
846 auto Qual = RT.getQualifiers();
847 switch (BuiltinID) {
848 case Builtin::BIto_global:
849 Qual.setAddressSpace(LangAS::opencl_global);
850 break;
851 case Builtin::BIto_local:
852 Qual.setAddressSpace(LangAS::opencl_local);
853 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000854 case Builtin::BIto_private:
855 Qual.setAddressSpace(LangAS::opencl_private);
856 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000857 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000858 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000859 }
860 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
861 RT.getUnqualifiedType(), Qual)));
862
863 return false;
864}
865
Reid Kleckneraa46ed92018-06-07 21:39:04 +0000866// Emit an error and return true if the current architecture is not in the list
867// of supported architectures.
868static bool
869CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
870 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
871 llvm::Triple::ArchType CurArch =
872 S.getASTContext().getTargetInfo().getTriple().getArch();
873 if (llvm::is_contained(SupportedArchs, CurArch))
874 return false;
875 S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported)
876 << TheCall->getSourceRange();
877 return true;
878}
879
John McCalldadc5752010-08-24 06:29:42 +0000880ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000881Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
882 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000883 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000884
Chris Lattner3be167f2010-10-01 23:23:24 +0000885 // Find out if any arguments are required to be integer constant expressions.
886 unsigned ICEArguments = 0;
887 ASTContext::GetBuiltinTypeError Error;
888 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
889 if (Error != ASTContext::GE_None)
890 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
891
892 // If any arguments are required to be ICE's, check and diagnose.
893 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
894 // Skip arguments not required to be ICE's.
895 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
896
897 llvm::APSInt Result;
898 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
899 return true;
900 ICEArguments &= ~(1 << ArgNo);
901 }
902
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000903 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000904 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000905 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000906 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000907 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000908 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000909 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000910 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000911 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000912 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000913 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000914 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000915 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000916 case Builtin::BI__va_start: {
917 switch (Context.getTargetInfo().getTriple().getArch()) {
918 case llvm::Triple::arm:
919 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000920 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000921 return ExprError();
922 break;
923 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000924 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000925 return ExprError();
926 break;
927 }
928 break;
929 }
Reid Kleckneraa46ed92018-06-07 21:39:04 +0000930
931 // The acquire, release, and no fence variants are ARM and AArch64 only.
932 case Builtin::BI_interlockedbittestandset_acq:
933 case Builtin::BI_interlockedbittestandset_rel:
934 case Builtin::BI_interlockedbittestandset_nf:
935 case Builtin::BI_interlockedbittestandreset_acq:
936 case Builtin::BI_interlockedbittestandreset_rel:
937 case Builtin::BI_interlockedbittestandreset_nf:
938 if (CheckBuiltinTargetSupport(
939 *this, BuiltinID, TheCall,
940 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
941 return ExprError();
942 break;
943
944 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
945 case Builtin::BI_bittest64:
946 case Builtin::BI_bittestandcomplement64:
947 case Builtin::BI_bittestandreset64:
948 case Builtin::BI_bittestandset64:
949 case Builtin::BI_interlockedbittestandreset64:
950 case Builtin::BI_interlockedbittestandset64:
951 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
952 {llvm::Triple::x86_64, llvm::Triple::arm,
953 llvm::Triple::thumb, llvm::Triple::aarch64}))
954 return ExprError();
955 break;
956
Chris Lattner2da14fb2007-12-20 00:26:33 +0000957 case Builtin::BI__builtin_isgreater:
958 case Builtin::BI__builtin_isgreaterequal:
959 case Builtin::BI__builtin_isless:
960 case Builtin::BI__builtin_islessequal:
961 case Builtin::BI__builtin_islessgreater:
962 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000963 if (SemaBuiltinUnorderedCompare(TheCall))
964 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000965 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000966 case Builtin::BI__builtin_fpclassify:
967 if (SemaBuiltinFPClassification(TheCall, 6))
968 return ExprError();
969 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000970 case Builtin::BI__builtin_isfinite:
971 case Builtin::BI__builtin_isinf:
972 case Builtin::BI__builtin_isinf_sign:
973 case Builtin::BI__builtin_isnan:
974 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000975 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000976 return ExprError();
977 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000978 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000979 return SemaBuiltinShuffleVector(TheCall);
980 // TheCall will be freed by the smart pointer here, but that's fine, since
981 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000982 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000983 if (SemaBuiltinPrefetch(TheCall))
984 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000985 break;
David Majnemer51169932016-10-31 05:37:48 +0000986 case Builtin::BI__builtin_alloca_with_align:
987 if (SemaBuiltinAllocaWithAlign(TheCall))
988 return ExprError();
989 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000990 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000991 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000992 if (SemaBuiltinAssume(TheCall))
993 return ExprError();
994 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000995 case Builtin::BI__builtin_assume_aligned:
996 if (SemaBuiltinAssumeAligned(TheCall))
997 return ExprError();
998 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000999 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +00001000 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001001 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001002 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001003 case Builtin::BI__builtin_longjmp:
1004 if (SemaBuiltinLongjmp(TheCall))
1005 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001006 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +00001007 case Builtin::BI__builtin_setjmp:
1008 if (SemaBuiltinSetjmp(TheCall))
1009 return ExprError();
1010 break;
David Majnemerc403a1c2015-03-20 17:03:35 +00001011 case Builtin::BI_setjmp:
1012 case Builtin::BI_setjmpex:
1013 if (checkArgCount(*this, TheCall, 1))
1014 return true;
1015 break;
John McCallbebede42011-02-26 05:39:39 +00001016 case Builtin::BI__builtin_classify_type:
1017 if (checkArgCount(*this, TheCall, 1)) return true;
1018 TheCall->setType(Context.IntTy);
1019 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +00001020 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +00001021 if (checkArgCount(*this, TheCall, 1)) return true;
1022 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +00001023 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001024 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00001025 case Builtin::BI__sync_fetch_and_add_1:
1026 case Builtin::BI__sync_fetch_and_add_2:
1027 case Builtin::BI__sync_fetch_and_add_4:
1028 case Builtin::BI__sync_fetch_and_add_8:
1029 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001030 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00001031 case Builtin::BI__sync_fetch_and_sub_1:
1032 case Builtin::BI__sync_fetch_and_sub_2:
1033 case Builtin::BI__sync_fetch_and_sub_4:
1034 case Builtin::BI__sync_fetch_and_sub_8:
1035 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001036 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00001037 case Builtin::BI__sync_fetch_and_or_1:
1038 case Builtin::BI__sync_fetch_and_or_2:
1039 case Builtin::BI__sync_fetch_and_or_4:
1040 case Builtin::BI__sync_fetch_and_or_8:
1041 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001042 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00001043 case Builtin::BI__sync_fetch_and_and_1:
1044 case Builtin::BI__sync_fetch_and_and_2:
1045 case Builtin::BI__sync_fetch_and_and_4:
1046 case Builtin::BI__sync_fetch_and_and_8:
1047 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001048 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00001049 case Builtin::BI__sync_fetch_and_xor_1:
1050 case Builtin::BI__sync_fetch_and_xor_2:
1051 case Builtin::BI__sync_fetch_and_xor_4:
1052 case Builtin::BI__sync_fetch_and_xor_8:
1053 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001054 case Builtin::BI__sync_fetch_and_nand:
1055 case Builtin::BI__sync_fetch_and_nand_1:
1056 case Builtin::BI__sync_fetch_and_nand_2:
1057 case Builtin::BI__sync_fetch_and_nand_4:
1058 case Builtin::BI__sync_fetch_and_nand_8:
1059 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001060 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001061 case Builtin::BI__sync_add_and_fetch_1:
1062 case Builtin::BI__sync_add_and_fetch_2:
1063 case Builtin::BI__sync_add_and_fetch_4:
1064 case Builtin::BI__sync_add_and_fetch_8:
1065 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001066 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001067 case Builtin::BI__sync_sub_and_fetch_1:
1068 case Builtin::BI__sync_sub_and_fetch_2:
1069 case Builtin::BI__sync_sub_and_fetch_4:
1070 case Builtin::BI__sync_sub_and_fetch_8:
1071 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001072 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001073 case Builtin::BI__sync_and_and_fetch_1:
1074 case Builtin::BI__sync_and_and_fetch_2:
1075 case Builtin::BI__sync_and_and_fetch_4:
1076 case Builtin::BI__sync_and_and_fetch_8:
1077 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001078 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001079 case Builtin::BI__sync_or_and_fetch_1:
1080 case Builtin::BI__sync_or_and_fetch_2:
1081 case Builtin::BI__sync_or_and_fetch_4:
1082 case Builtin::BI__sync_or_and_fetch_8:
1083 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001084 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001085 case Builtin::BI__sync_xor_and_fetch_1:
1086 case Builtin::BI__sync_xor_and_fetch_2:
1087 case Builtin::BI__sync_xor_and_fetch_4:
1088 case Builtin::BI__sync_xor_and_fetch_8:
1089 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001090 case Builtin::BI__sync_nand_and_fetch:
1091 case Builtin::BI__sync_nand_and_fetch_1:
1092 case Builtin::BI__sync_nand_and_fetch_2:
1093 case Builtin::BI__sync_nand_and_fetch_4:
1094 case Builtin::BI__sync_nand_and_fetch_8:
1095 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001096 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001097 case Builtin::BI__sync_val_compare_and_swap_1:
1098 case Builtin::BI__sync_val_compare_and_swap_2:
1099 case Builtin::BI__sync_val_compare_and_swap_4:
1100 case Builtin::BI__sync_val_compare_and_swap_8:
1101 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001102 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001103 case Builtin::BI__sync_bool_compare_and_swap_1:
1104 case Builtin::BI__sync_bool_compare_and_swap_2:
1105 case Builtin::BI__sync_bool_compare_and_swap_4:
1106 case Builtin::BI__sync_bool_compare_and_swap_8:
1107 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001108 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001109 case Builtin::BI__sync_lock_test_and_set_1:
1110 case Builtin::BI__sync_lock_test_and_set_2:
1111 case Builtin::BI__sync_lock_test_and_set_4:
1112 case Builtin::BI__sync_lock_test_and_set_8:
1113 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001114 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001115 case Builtin::BI__sync_lock_release_1:
1116 case Builtin::BI__sync_lock_release_2:
1117 case Builtin::BI__sync_lock_release_4:
1118 case Builtin::BI__sync_lock_release_8:
1119 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001120 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001121 case Builtin::BI__sync_swap_1:
1122 case Builtin::BI__sync_swap_2:
1123 case Builtin::BI__sync_swap_4:
1124 case Builtin::BI__sync_swap_8:
1125 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001126 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001127 case Builtin::BI__builtin_nontemporal_load:
1128 case Builtin::BI__builtin_nontemporal_store:
1129 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001130#define BUILTIN(ID, TYPE, ATTRS)
1131#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1132 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001133 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001134#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001135 case Builtin::BI__annotation:
1136 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1137 return ExprError();
1138 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001139 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001140 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001141 return ExprError();
1142 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001143 case Builtin::BI__builtin_addressof:
1144 if (SemaBuiltinAddressof(*this, TheCall))
1145 return ExprError();
1146 break;
John McCall03107a42015-10-29 20:48:01 +00001147 case Builtin::BI__builtin_add_overflow:
1148 case Builtin::BI__builtin_sub_overflow:
1149 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001150 if (SemaBuiltinOverflow(*this, TheCall))
1151 return ExprError();
1152 break;
Richard Smith760520b2014-06-03 23:27:44 +00001153 case Builtin::BI__builtin_operator_new:
Eric Fiselierfa752f22018-03-21 19:19:48 +00001154 case Builtin::BI__builtin_operator_delete: {
1155 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1156 ExprResult Res =
1157 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1158 if (Res.isInvalid())
1159 CorrectDelayedTyposInExpr(TheCallResult.get());
1160 return Res;
1161 }
Aaron Ballman06525342018-04-10 21:58:13 +00001162 case Builtin::BI__builtin_dump_struct: {
1163 // We first want to ensure we are called with 2 arguments
1164 if (checkArgCount(*this, TheCall, 2))
1165 return ExprError();
1166 // Ensure that the first argument is of type 'struct XX *'
1167 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1168 const QualType PtrArgType = PtrArg->getType();
1169 if (!PtrArgType->isPointerType() ||
1170 !PtrArgType->getPointeeType()->isRecordType()) {
1171 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1172 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1173 << "structure pointer";
1174 return ExprError();
1175 }
1176
1177 // Ensure that the second argument is of type 'FunctionType'
1178 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1179 const QualType FnPtrArgType = FnPtrArg->getType();
1180 if (!FnPtrArgType->isPointerType()) {
1181 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1182 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1183 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1184 return ExprError();
1185 }
1186
1187 const auto *FuncType =
1188 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1189
1190 if (!FuncType) {
1191 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1192 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1193 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1194 return ExprError();
1195 }
1196
1197 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1198 if (!FT->getNumParams()) {
1199 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1200 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1201 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1202 return ExprError();
1203 }
1204 QualType PT = FT->getParamType(0);
1205 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1206 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1207 !PT->getPointeeType().isConstQualified()) {
1208 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1209 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1210 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1211 return ExprError();
1212 }
1213 }
1214
1215 TheCall->setType(Context.IntTy);
1216 break;
1217 }
1218
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001219 // check secure string manipulation functions where overflows
1220 // are detectable at compile time
1221 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001222 case Builtin::BI__builtin___memmove_chk:
1223 case Builtin::BI__builtin___memset_chk:
1224 case Builtin::BI__builtin___strlcat_chk:
1225 case Builtin::BI__builtin___strlcpy_chk:
1226 case Builtin::BI__builtin___strncat_chk:
1227 case Builtin::BI__builtin___strncpy_chk:
1228 case Builtin::BI__builtin___stpncpy_chk:
1229 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1230 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001231 case Builtin::BI__builtin___memccpy_chk:
1232 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1233 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001234 case Builtin::BI__builtin___snprintf_chk:
1235 case Builtin::BI__builtin___vsnprintf_chk:
1236 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1237 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001238 case Builtin::BI__builtin_call_with_static_chain:
1239 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1240 return ExprError();
1241 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001242 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001243 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001244 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1245 diag::err_seh___except_block))
1246 return ExprError();
1247 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001248 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001249 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001250 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1251 diag::err_seh___except_filter))
1252 return ExprError();
1253 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001254 case Builtin::BI__GetExceptionInfo:
1255 if (checkArgCount(*this, TheCall, 1))
1256 return ExprError();
1257
1258 if (CheckCXXThrowOperand(
1259 TheCall->getLocStart(),
1260 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1261 TheCall))
1262 return ExprError();
1263
1264 TheCall->setType(Context.VoidPtrTy);
1265 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001266 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001267 case Builtin::BIread_pipe:
1268 case Builtin::BIwrite_pipe:
1269 // Since those two functions are declared with var args, we need a semantic
1270 // check for the argument.
1271 if (SemaBuiltinRWPipe(*this, TheCall))
1272 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001273 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001274 break;
1275 case Builtin::BIreserve_read_pipe:
1276 case Builtin::BIreserve_write_pipe:
1277 case Builtin::BIwork_group_reserve_read_pipe:
1278 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001279 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1280 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001281 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001282 case Builtin::BIsub_group_reserve_read_pipe:
1283 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001284 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1285 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001286 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001287 break;
1288 case Builtin::BIcommit_read_pipe:
1289 case Builtin::BIcommit_write_pipe:
1290 case Builtin::BIwork_group_commit_read_pipe:
1291 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001292 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1293 return ExprError();
1294 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001295 case Builtin::BIsub_group_commit_read_pipe:
1296 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001297 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1298 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001299 return ExprError();
1300 break;
1301 case Builtin::BIget_pipe_num_packets:
1302 case Builtin::BIget_pipe_max_packets:
1303 if (SemaBuiltinPipePackets(*this, TheCall))
1304 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001305 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001306 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001307 case Builtin::BIto_global:
1308 case Builtin::BIto_local:
1309 case Builtin::BIto_private:
1310 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1311 return ExprError();
1312 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001313 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1314 case Builtin::BIenqueue_kernel:
1315 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1316 return ExprError();
1317 break;
1318 case Builtin::BIget_kernel_work_group_size:
1319 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1320 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1321 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001322 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001323 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1324 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1325 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1326 return ExprError();
1327 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001328 case Builtin::BI__builtin_os_log_format:
1329 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001330 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001331 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001332 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001333 }
Richard Smith760520b2014-06-03 23:27:44 +00001334
Nate Begeman4904e322010-06-08 02:47:44 +00001335 // Since the target specific builtins for each arch overlap, only check those
1336 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001337 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001338 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001339 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001340 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001341 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001342 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001343 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1344 return ExprError();
1345 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001346 case llvm::Triple::aarch64:
1347 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001348 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001349 return ExprError();
1350 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001351 case llvm::Triple::hexagon:
1352 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1353 return ExprError();
1354 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001355 case llvm::Triple::mips:
1356 case llvm::Triple::mipsel:
1357 case llvm::Triple::mips64:
1358 case llvm::Triple::mips64el:
1359 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1360 return ExprError();
1361 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001362 case llvm::Triple::systemz:
1363 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1364 return ExprError();
1365 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001366 case llvm::Triple::x86:
1367 case llvm::Triple::x86_64:
1368 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1369 return ExprError();
1370 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001371 case llvm::Triple::ppc:
1372 case llvm::Triple::ppc64:
1373 case llvm::Triple::ppc64le:
1374 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1375 return ExprError();
1376 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001377 default:
1378 break;
1379 }
1380 }
1381
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001382 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001383}
1384
Nate Begeman91e1fea2010-06-14 05:21:25 +00001385// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001386static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001387 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001388 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001389 switch (Type.getEltType()) {
1390 case NeonTypeFlags::Int8:
1391 case NeonTypeFlags::Poly8:
1392 return shift ? 7 : (8 << IsQuad) - 1;
1393 case NeonTypeFlags::Int16:
1394 case NeonTypeFlags::Poly16:
1395 return shift ? 15 : (4 << IsQuad) - 1;
1396 case NeonTypeFlags::Int32:
1397 return shift ? 31 : (2 << IsQuad) - 1;
1398 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001399 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001400 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001401 case NeonTypeFlags::Poly128:
1402 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001403 case NeonTypeFlags::Float16:
1404 assert(!shift && "cannot shift float types!");
1405 return (4 << IsQuad) - 1;
1406 case NeonTypeFlags::Float32:
1407 assert(!shift && "cannot shift float types!");
1408 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001409 case NeonTypeFlags::Float64:
1410 assert(!shift && "cannot shift float types!");
1411 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001412 }
David Blaikie8a40f702012-01-17 06:56:22 +00001413 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001414}
1415
Bob Wilsone4d77232011-11-08 05:04:11 +00001416/// getNeonEltType - Return the QualType corresponding to the elements of
1417/// the vector type specified by the NeonTypeFlags. This is used to check
1418/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001419static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001420 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001421 switch (Flags.getEltType()) {
1422 case NeonTypeFlags::Int8:
1423 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1424 case NeonTypeFlags::Int16:
1425 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1426 case NeonTypeFlags::Int32:
1427 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1428 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001429 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001430 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1431 else
1432 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1433 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001434 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001435 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001436 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001437 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001438 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001439 if (IsInt64Long)
1440 return Context.UnsignedLongTy;
1441 else
1442 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001443 case NeonTypeFlags::Poly128:
1444 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001445 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001446 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001447 case NeonTypeFlags::Float32:
1448 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001449 case NeonTypeFlags::Float64:
1450 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001451 }
David Blaikie8a40f702012-01-17 06:56:22 +00001452 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001453}
1454
Tim Northover12670412014-02-19 10:37:05 +00001455bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001456 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001457 uint64_t mask = 0;
1458 unsigned TV = 0;
1459 int PtrArgNum = -1;
1460 bool HasConstPtr = false;
1461 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001462#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001463#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001464#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001465#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001466 }
1467
1468 // For NEON intrinsics which are overloaded on vector element type, validate
1469 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001470 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001471 if (mask) {
1472 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1473 return true;
1474
1475 TV = Result.getLimitedValue(64);
1476 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1477 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001478 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001479 }
1480
1481 if (PtrArgNum >= 0) {
1482 // Check that pointer arguments have the specified type.
1483 Expr *Arg = TheCall->getArg(PtrArgNum);
1484 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1485 Arg = ICE->getSubExpr();
1486 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1487 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001488
Tim Northovera2ee4332014-03-29 15:09:45 +00001489 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001490 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1491 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001492 bool IsInt64Long =
1493 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1494 QualType EltTy =
1495 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001496 if (HasConstPtr)
1497 EltTy = EltTy.withConst();
1498 QualType LHSTy = Context.getPointerType(EltTy);
1499 AssignConvertType ConvTy;
1500 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1501 if (RHS.isInvalid())
1502 return true;
1503 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1504 RHS.get(), AA_Assigning))
1505 return true;
1506 }
1507
1508 // For NEON intrinsics which take an immediate value as part of the
1509 // instruction, range check them here.
1510 unsigned i = 0, l = 0, u = 0;
1511 switch (BuiltinID) {
1512 default:
1513 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001514 #define GET_NEON_IMMEDIATE_CHECK
1515 #include "clang/Basic/arm_neon.inc"
1516 #include "clang/Basic/arm_fp16.inc"
1517 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001518 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001519
Richard Sandiford28940af2014-04-16 08:47:51 +00001520 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001521}
1522
Tim Northovera2ee4332014-03-29 15:09:45 +00001523bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1524 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001525 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001526 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001527 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001528 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001529 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001530 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1531 BuiltinID == AArch64::BI__builtin_arm_strex ||
1532 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001533 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001534 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001535 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1536 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1537 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001538
1539 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1540
1541 // Ensure that we have the proper number of arguments.
1542 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1543 return true;
1544
1545 // Inspect the pointer argument of the atomic builtin. This should always be
1546 // a pointer type, whose element is an integral scalar or pointer type.
1547 // Because it is a pointer type, we don't have to worry about any implicit
1548 // casts here.
1549 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1550 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1551 if (PointerArgRes.isInvalid())
1552 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001553 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001554
1555 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1556 if (!pointerType) {
1557 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1558 << PointerArg->getType() << PointerArg->getSourceRange();
1559 return true;
1560 }
1561
1562 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1563 // task is to insert the appropriate casts into the AST. First work out just
1564 // what the appropriate type is.
1565 QualType ValType = pointerType->getPointeeType();
1566 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1567 if (IsLdrex)
1568 AddrType.addConst();
1569
1570 // Issue a warning if the cast is dodgy.
1571 CastKind CastNeeded = CK_NoOp;
1572 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1573 CastNeeded = CK_BitCast;
1574 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1575 << PointerArg->getType()
1576 << Context.getPointerType(AddrType)
1577 << AA_Passing << PointerArg->getSourceRange();
1578 }
1579
1580 // Finally, do the cast and replace the argument with the corrected version.
1581 AddrType = Context.getPointerType(AddrType);
1582 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1583 if (PointerArgRes.isInvalid())
1584 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001585 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001586
1587 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1588
1589 // In general, we allow ints, floats and pointers to be loaded and stored.
1590 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1591 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1592 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1593 << PointerArg->getType() << PointerArg->getSourceRange();
1594 return true;
1595 }
1596
1597 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001598 if (Context.getTypeSize(ValType) > MaxWidth) {
1599 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001600 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1601 << PointerArg->getType() << PointerArg->getSourceRange();
1602 return true;
1603 }
1604
1605 switch (ValType.getObjCLifetime()) {
1606 case Qualifiers::OCL_None:
1607 case Qualifiers::OCL_ExplicitNone:
1608 // okay
1609 break;
1610
1611 case Qualifiers::OCL_Weak:
1612 case Qualifiers::OCL_Strong:
1613 case Qualifiers::OCL_Autoreleasing:
1614 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1615 << ValType << PointerArg->getSourceRange();
1616 return true;
1617 }
1618
Tim Northover6aacd492013-07-16 09:47:53 +00001619 if (IsLdrex) {
1620 TheCall->setType(ValType);
1621 return false;
1622 }
1623
1624 // Initialize the argument to be stored.
1625 ExprResult ValArg = TheCall->getArg(0);
1626 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1627 Context, ValType, /*consume*/ false);
1628 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1629 if (ValArg.isInvalid())
1630 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001631 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001632
1633 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1634 // but the custom checker bypasses all default analysis.
1635 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001636 return false;
1637}
1638
Nate Begeman4904e322010-06-08 02:47:44 +00001639bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001640 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001641 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1642 BuiltinID == ARM::BI__builtin_arm_strex ||
1643 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001644 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001645 }
1646
Yi Kong26d104a2014-08-13 19:18:14 +00001647 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1648 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1649 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1650 }
1651
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001652 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1653 BuiltinID == ARM::BI__builtin_arm_wsr64)
1654 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1655
1656 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1657 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1658 BuiltinID == ARM::BI__builtin_arm_wsr ||
1659 BuiltinID == ARM::BI__builtin_arm_wsrp)
1660 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1661
Tim Northover12670412014-02-19 10:37:05 +00001662 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1663 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001664
Yi Kong4efadfb2014-07-03 16:01:25 +00001665 // For intrinsics which take an immediate value as part of the instruction,
1666 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001667 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001668 switch (BuiltinID) {
1669 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001670 case ARM::BI__builtin_arm_ssat:
1671 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1672 case ARM::BI__builtin_arm_usat:
1673 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1674 case ARM::BI__builtin_arm_ssat16:
1675 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1676 case ARM::BI__builtin_arm_usat16:
1677 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001678 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001679 case ARM::BI__builtin_arm_vcvtr_d:
1680 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001681 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001682 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001683 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001684 case ARM::BI__builtin_arm_dbg:
1685 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001686 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001687}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001688
Tim Northover573cbee2014-05-24 12:52:07 +00001689bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001690 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001691 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001692 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1693 BuiltinID == AArch64::BI__builtin_arm_strex ||
1694 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001695 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1696 }
1697
Yi Konga5548432014-08-13 19:18:20 +00001698 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1699 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1700 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1701 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1702 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1703 }
1704
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001705 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1706 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001707 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001708
1709 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1710 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1711 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1712 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1713 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1714
Tim Northovera2ee4332014-03-29 15:09:45 +00001715 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1716 return true;
1717
Yi Kong19a29ac2014-07-17 10:52:06 +00001718 // For intrinsics which take an immediate value as part of the instruction,
1719 // range check them here.
1720 unsigned i = 0, l = 0, u = 0;
1721 switch (BuiltinID) {
1722 default: return false;
1723 case AArch64::BI__builtin_arm_dmb:
1724 case AArch64::BI__builtin_arm_dsb:
1725 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1726 }
1727
Yi Kong19a29ac2014-07-17 10:52:06 +00001728 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001729}
1730
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001731bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1732 CallExpr *TheCall) {
1733 struct ArgInfo {
1734 ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1735 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1736 unsigned OpNum = 0;
1737 bool IsSigned = false;
1738 unsigned BitWidth = 0;
1739 unsigned Align = 0;
1740 };
1741
1742 static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1743 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
1744 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
1745 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
1746 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
1747 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
1748 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
1749 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
1750 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
1751 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
1752 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
1753 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
1754
1755 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
1756 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
1757 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
1758 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
1759 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
1760 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
1761 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
1762 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
1763 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
1764 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
1765 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
1766
1767 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
1768 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
1769 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
1770 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
1771 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
1772 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
1773 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
1774 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
1775 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
1776 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
1777 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
1778 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
1779 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
1780 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
1781 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
1782 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
1783 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
1784 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
1785 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
1786 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
1787 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
1788 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
1789 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
1790 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
1791 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
1792 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
1793 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
1794 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
1795 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
1796 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
1797 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
1798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
1799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
1800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
1801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
1802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
1803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
1804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
1805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
1806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
1807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
1808 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
1809 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
1810 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
1811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
1812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
1813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
1814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
1815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
1816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
1817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
1818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1819 {{ 1, false, 6, 0 }} },
1820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
1821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
1822 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
1823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
1824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
1825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
1826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1827 {{ 1, false, 5, 0 }} },
1828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
1829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
1830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
1831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
1832 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
1833 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
1834 { 2, false, 5, 0 }} },
1835 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
1836 { 2, false, 6, 0 }} },
1837 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
1838 { 3, false, 5, 0 }} },
1839 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
1840 { 3, false, 6, 0 }} },
1841 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
1842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
1843 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
1844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
1845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
1846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
1847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
1848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
1849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
1850 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
1851 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
1852 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
1853 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
1854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
1855 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
1856 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1857 {{ 2, false, 4, 0 },
1858 { 3, false, 5, 0 }} },
1859 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1860 {{ 2, false, 4, 0 },
1861 { 3, false, 5, 0 }} },
1862 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1863 {{ 2, false, 4, 0 },
1864 { 3, false, 5, 0 }} },
1865 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1866 {{ 2, false, 4, 0 },
1867 { 3, false, 5, 0 }} },
1868 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
1869 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
1870 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
1871 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
1872 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
1873 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
1874 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
1875 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
1876 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
1877 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
1878 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
1879 { 2, false, 5, 0 }} },
1880 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
1881 { 2, false, 6, 0 }} },
1882 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
1883 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
1884 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
1885 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
1886 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
1887 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
1888 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
1889 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
1890 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1891 {{ 1, false, 4, 0 }} },
1892 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
1893 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1894 {{ 1, false, 4, 0 }} },
1895 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
1896 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
1897 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
1898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
1899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
1900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
1901 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
1902 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
1903 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
1904 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
1905 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
1906 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
1907 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
1908 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
1909 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
1910 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
1911 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
1912 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
1913 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
1914 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1915 {{ 3, false, 1, 0 }} },
1916 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
1917 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
1918 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
1919 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1920 {{ 3, false, 1, 0 }} },
1921 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
1922 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
1923 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
1924 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1925 {{ 3, false, 1, 0 }} },
1926 };
1927
1928 auto F = Infos.find(BuiltinID);
1929 if (F == Infos.end())
1930 return false;
1931
1932 bool Error = false;
1933
1934 for (const ArgInfo &A : F->second) {
1935 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1936 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1937 if (!A.Align) {
1938 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1939 } else {
1940 unsigned M = 1 << A.Align;
1941 Min *= M;
1942 Max *= M;
1943 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1944 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1945 }
1946 }
1947 return Error;
1948}
1949
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001950// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1951// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1952// ordering for DSP is unspecified. MSA is ordered by the data format used
1953// by the underlying instruction i.e., df/m, df/n and then by size.
1954//
1955// FIXME: The size tests here should instead be tablegen'd along with the
1956// definitions from include/clang/Basic/BuiltinsMips.def.
1957// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1958// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001959bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001960 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001961 switch (BuiltinID) {
1962 default: return false;
1963 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1964 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001965 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1966 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1967 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1968 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1969 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001970 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1971 // df/m field.
1972 // These intrinsics take an unsigned 3 bit immediate.
1973 case Mips::BI__builtin_msa_bclri_b:
1974 case Mips::BI__builtin_msa_bnegi_b:
1975 case Mips::BI__builtin_msa_bseti_b:
1976 case Mips::BI__builtin_msa_sat_s_b:
1977 case Mips::BI__builtin_msa_sat_u_b:
1978 case Mips::BI__builtin_msa_slli_b:
1979 case Mips::BI__builtin_msa_srai_b:
1980 case Mips::BI__builtin_msa_srari_b:
1981 case Mips::BI__builtin_msa_srli_b:
1982 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1983 case Mips::BI__builtin_msa_binsli_b:
1984 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1985 // These intrinsics take an unsigned 4 bit immediate.
1986 case Mips::BI__builtin_msa_bclri_h:
1987 case Mips::BI__builtin_msa_bnegi_h:
1988 case Mips::BI__builtin_msa_bseti_h:
1989 case Mips::BI__builtin_msa_sat_s_h:
1990 case Mips::BI__builtin_msa_sat_u_h:
1991 case Mips::BI__builtin_msa_slli_h:
1992 case Mips::BI__builtin_msa_srai_h:
1993 case Mips::BI__builtin_msa_srari_h:
1994 case Mips::BI__builtin_msa_srli_h:
1995 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1996 case Mips::BI__builtin_msa_binsli_h:
1997 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001998 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001999 // The first block of intrinsics actually have an unsigned 5 bit field,
2000 // not a df/n field.
2001 case Mips::BI__builtin_msa_clei_u_b:
2002 case Mips::BI__builtin_msa_clei_u_h:
2003 case Mips::BI__builtin_msa_clei_u_w:
2004 case Mips::BI__builtin_msa_clei_u_d:
2005 case Mips::BI__builtin_msa_clti_u_b:
2006 case Mips::BI__builtin_msa_clti_u_h:
2007 case Mips::BI__builtin_msa_clti_u_w:
2008 case Mips::BI__builtin_msa_clti_u_d:
2009 case Mips::BI__builtin_msa_maxi_u_b:
2010 case Mips::BI__builtin_msa_maxi_u_h:
2011 case Mips::BI__builtin_msa_maxi_u_w:
2012 case Mips::BI__builtin_msa_maxi_u_d:
2013 case Mips::BI__builtin_msa_mini_u_b:
2014 case Mips::BI__builtin_msa_mini_u_h:
2015 case Mips::BI__builtin_msa_mini_u_w:
2016 case Mips::BI__builtin_msa_mini_u_d:
2017 case Mips::BI__builtin_msa_addvi_b:
2018 case Mips::BI__builtin_msa_addvi_h:
2019 case Mips::BI__builtin_msa_addvi_w:
2020 case Mips::BI__builtin_msa_addvi_d:
2021 case Mips::BI__builtin_msa_bclri_w:
2022 case Mips::BI__builtin_msa_bnegi_w:
2023 case Mips::BI__builtin_msa_bseti_w:
2024 case Mips::BI__builtin_msa_sat_s_w:
2025 case Mips::BI__builtin_msa_sat_u_w:
2026 case Mips::BI__builtin_msa_slli_w:
2027 case Mips::BI__builtin_msa_srai_w:
2028 case Mips::BI__builtin_msa_srari_w:
2029 case Mips::BI__builtin_msa_srli_w:
2030 case Mips::BI__builtin_msa_srlri_w:
2031 case Mips::BI__builtin_msa_subvi_b:
2032 case Mips::BI__builtin_msa_subvi_h:
2033 case Mips::BI__builtin_msa_subvi_w:
2034 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2035 case Mips::BI__builtin_msa_binsli_w:
2036 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2037 // These intrinsics take an unsigned 6 bit immediate.
2038 case Mips::BI__builtin_msa_bclri_d:
2039 case Mips::BI__builtin_msa_bnegi_d:
2040 case Mips::BI__builtin_msa_bseti_d:
2041 case Mips::BI__builtin_msa_sat_s_d:
2042 case Mips::BI__builtin_msa_sat_u_d:
2043 case Mips::BI__builtin_msa_slli_d:
2044 case Mips::BI__builtin_msa_srai_d:
2045 case Mips::BI__builtin_msa_srari_d:
2046 case Mips::BI__builtin_msa_srli_d:
2047 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2048 case Mips::BI__builtin_msa_binsli_d:
2049 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2050 // These intrinsics take a signed 5 bit immediate.
2051 case Mips::BI__builtin_msa_ceqi_b:
2052 case Mips::BI__builtin_msa_ceqi_h:
2053 case Mips::BI__builtin_msa_ceqi_w:
2054 case Mips::BI__builtin_msa_ceqi_d:
2055 case Mips::BI__builtin_msa_clti_s_b:
2056 case Mips::BI__builtin_msa_clti_s_h:
2057 case Mips::BI__builtin_msa_clti_s_w:
2058 case Mips::BI__builtin_msa_clti_s_d:
2059 case Mips::BI__builtin_msa_clei_s_b:
2060 case Mips::BI__builtin_msa_clei_s_h:
2061 case Mips::BI__builtin_msa_clei_s_w:
2062 case Mips::BI__builtin_msa_clei_s_d:
2063 case Mips::BI__builtin_msa_maxi_s_b:
2064 case Mips::BI__builtin_msa_maxi_s_h:
2065 case Mips::BI__builtin_msa_maxi_s_w:
2066 case Mips::BI__builtin_msa_maxi_s_d:
2067 case Mips::BI__builtin_msa_mini_s_b:
2068 case Mips::BI__builtin_msa_mini_s_h:
2069 case Mips::BI__builtin_msa_mini_s_w:
2070 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2071 // These intrinsics take an unsigned 8 bit immediate.
2072 case Mips::BI__builtin_msa_andi_b:
2073 case Mips::BI__builtin_msa_nori_b:
2074 case Mips::BI__builtin_msa_ori_b:
2075 case Mips::BI__builtin_msa_shf_b:
2076 case Mips::BI__builtin_msa_shf_h:
2077 case Mips::BI__builtin_msa_shf_w:
2078 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2079 case Mips::BI__builtin_msa_bseli_b:
2080 case Mips::BI__builtin_msa_bmnzi_b:
2081 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2082 // df/n format
2083 // These intrinsics take an unsigned 4 bit immediate.
2084 case Mips::BI__builtin_msa_copy_s_b:
2085 case Mips::BI__builtin_msa_copy_u_b:
2086 case Mips::BI__builtin_msa_insve_b:
2087 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002088 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2089 // These intrinsics take an unsigned 3 bit immediate.
2090 case Mips::BI__builtin_msa_copy_s_h:
2091 case Mips::BI__builtin_msa_copy_u_h:
2092 case Mips::BI__builtin_msa_insve_h:
2093 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002094 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2095 // These intrinsics take an unsigned 2 bit immediate.
2096 case Mips::BI__builtin_msa_copy_s_w:
2097 case Mips::BI__builtin_msa_copy_u_w:
2098 case Mips::BI__builtin_msa_insve_w:
2099 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002100 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2101 // These intrinsics take an unsigned 1 bit immediate.
2102 case Mips::BI__builtin_msa_copy_s_d:
2103 case Mips::BI__builtin_msa_copy_u_d:
2104 case Mips::BI__builtin_msa_insve_d:
2105 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002106 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2107 // Memory offsets and immediate loads.
2108 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00002109 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002110 case Mips::BI__builtin_msa_ldi_h:
2111 case Mips::BI__builtin_msa_ldi_w:
2112 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2113 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2114 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2115 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2116 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2117 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2118 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2119 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2120 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00002121 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002122
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002123 if (!m)
2124 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2125
2126 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2127 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002128}
2129
Kit Bartone50adcb2015-03-30 19:40:59 +00002130bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2131 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00002132 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2133 BuiltinID == PPC::BI__builtin_divdeu ||
2134 BuiltinID == PPC::BI__builtin_bpermd;
2135 bool IsTarget64Bit = Context.getTargetInfo()
2136 .getTypeWidth(Context
2137 .getTargetInfo()
2138 .getIntPtrType()) == 64;
2139 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2140 BuiltinID == PPC::BI__builtin_divweu ||
2141 BuiltinID == PPC::BI__builtin_divde ||
2142 BuiltinID == PPC::BI__builtin_divdeu;
2143
2144 if (Is64BitBltin && !IsTarget64Bit)
2145 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2146 << TheCall->getSourceRange();
2147
2148 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2149 (BuiltinID == PPC::BI__builtin_bpermd &&
2150 !Context.getTargetInfo().hasFeature("bpermd")))
2151 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2152 << TheCall->getSourceRange();
2153
Kit Bartone50adcb2015-03-30 19:40:59 +00002154 switch (BuiltinID) {
2155 default: return false;
2156 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2157 case PPC::BI__builtin_altivec_crypto_vshasigmad:
2158 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2159 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2160 case PPC::BI__builtin_tbegin:
2161 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2162 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2163 case PPC::BI__builtin_tabortwc:
2164 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2165 case PPC::BI__builtin_tabortwci:
2166 case PPC::BI__builtin_tabortdci:
2167 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2168 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00002169 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00002170 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00002171 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00002172 }
2173 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2174}
2175
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002176bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2177 CallExpr *TheCall) {
2178 if (BuiltinID == SystemZ::BI__builtin_tabort) {
2179 Expr *Arg = TheCall->getArg(0);
2180 llvm::APSInt AbortCode(32);
2181 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2182 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2183 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2184 << Arg->getSourceRange();
2185 }
2186
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002187 // For intrinsics which take an immediate value as part of the instruction,
2188 // range check them here.
2189 unsigned i = 0, l = 0, u = 0;
2190 switch (BuiltinID) {
2191 default: return false;
2192 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2193 case SystemZ::BI__builtin_s390_verimb:
2194 case SystemZ::BI__builtin_s390_verimh:
2195 case SystemZ::BI__builtin_s390_verimf:
2196 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2197 case SystemZ::BI__builtin_s390_vfaeb:
2198 case SystemZ::BI__builtin_s390_vfaeh:
2199 case SystemZ::BI__builtin_s390_vfaef:
2200 case SystemZ::BI__builtin_s390_vfaebs:
2201 case SystemZ::BI__builtin_s390_vfaehs:
2202 case SystemZ::BI__builtin_s390_vfaefs:
2203 case SystemZ::BI__builtin_s390_vfaezb:
2204 case SystemZ::BI__builtin_s390_vfaezh:
2205 case SystemZ::BI__builtin_s390_vfaezf:
2206 case SystemZ::BI__builtin_s390_vfaezbs:
2207 case SystemZ::BI__builtin_s390_vfaezhs:
2208 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002209 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002210 case SystemZ::BI__builtin_s390_vfidb:
2211 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2212 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002213 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002214 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2215 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2216 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2217 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2218 case SystemZ::BI__builtin_s390_vstrcb:
2219 case SystemZ::BI__builtin_s390_vstrch:
2220 case SystemZ::BI__builtin_s390_vstrcf:
2221 case SystemZ::BI__builtin_s390_vstrczb:
2222 case SystemZ::BI__builtin_s390_vstrczh:
2223 case SystemZ::BI__builtin_s390_vstrczf:
2224 case SystemZ::BI__builtin_s390_vstrcbs:
2225 case SystemZ::BI__builtin_s390_vstrchs:
2226 case SystemZ::BI__builtin_s390_vstrcfs:
2227 case SystemZ::BI__builtin_s390_vstrczbs:
2228 case SystemZ::BI__builtin_s390_vstrczhs:
2229 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002230 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2231 case SystemZ::BI__builtin_s390_vfminsb:
2232 case SystemZ::BI__builtin_s390_vfmaxsb:
2233 case SystemZ::BI__builtin_s390_vfmindb:
2234 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002235 }
2236 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002237}
2238
Craig Topper5ba2c502015-11-07 08:08:31 +00002239/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2240/// This checks that the target supports __builtin_cpu_supports and
2241/// that the string argument is constant and valid.
2242static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2243 Expr *Arg = TheCall->getArg(0);
2244
2245 // Check if the argument is a string literal.
2246 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2247 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2248 << Arg->getSourceRange();
2249
2250 // Check the contents of the string.
2251 StringRef Feature =
2252 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2253 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2254 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2255 << Arg->getSourceRange();
2256 return false;
2257}
2258
Craig Topper699ae0c2017-08-10 20:28:30 +00002259/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2260/// This checks that the target supports __builtin_cpu_is and
2261/// that the string argument is constant and valid.
2262static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2263 Expr *Arg = TheCall->getArg(0);
2264
2265 // Check if the argument is a string literal.
2266 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2267 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2268 << Arg->getSourceRange();
2269
2270 // Check the contents of the string.
2271 StringRef Feature =
2272 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2273 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2274 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2275 << Arg->getSourceRange();
2276 return false;
2277}
2278
Craig Toppera7e253e2016-09-23 04:48:31 +00002279// Check if the rounding mode is legal.
2280bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2281 // Indicates if this instruction has rounding control or just SAE.
2282 bool HasRC = false;
2283
2284 unsigned ArgNum = 0;
2285 switch (BuiltinID) {
2286 default:
2287 return false;
2288 case X86::BI__builtin_ia32_vcvttsd2si32:
2289 case X86::BI__builtin_ia32_vcvttsd2si64:
2290 case X86::BI__builtin_ia32_vcvttsd2usi32:
2291 case X86::BI__builtin_ia32_vcvttsd2usi64:
2292 case X86::BI__builtin_ia32_vcvttss2si32:
2293 case X86::BI__builtin_ia32_vcvttss2si64:
2294 case X86::BI__builtin_ia32_vcvttss2usi32:
2295 case X86::BI__builtin_ia32_vcvttss2usi64:
2296 ArgNum = 1;
2297 break;
2298 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2299 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2300 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2301 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2302 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2303 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2304 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2305 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2306 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2307 case X86::BI__builtin_ia32_exp2pd_mask:
2308 case X86::BI__builtin_ia32_exp2ps_mask:
2309 case X86::BI__builtin_ia32_getexppd512_mask:
2310 case X86::BI__builtin_ia32_getexpps512_mask:
2311 case X86::BI__builtin_ia32_rcp28pd_mask:
2312 case X86::BI__builtin_ia32_rcp28ps_mask:
2313 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2314 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2315 case X86::BI__builtin_ia32_vcomisd:
2316 case X86::BI__builtin_ia32_vcomiss:
2317 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2318 ArgNum = 3;
2319 break;
2320 case X86::BI__builtin_ia32_cmppd512_mask:
2321 case X86::BI__builtin_ia32_cmpps512_mask:
2322 case X86::BI__builtin_ia32_cmpsd_mask:
2323 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002324 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002325 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2326 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002327 case X86::BI__builtin_ia32_maxpd512_mask:
2328 case X86::BI__builtin_ia32_maxps512_mask:
2329 case X86::BI__builtin_ia32_maxsd_round_mask:
2330 case X86::BI__builtin_ia32_maxss_round_mask:
2331 case X86::BI__builtin_ia32_minpd512_mask:
2332 case X86::BI__builtin_ia32_minps512_mask:
2333 case X86::BI__builtin_ia32_minsd_round_mask:
2334 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002335 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2336 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2337 case X86::BI__builtin_ia32_reducepd512_mask:
2338 case X86::BI__builtin_ia32_reduceps512_mask:
2339 case X86::BI__builtin_ia32_rndscalepd_mask:
2340 case X86::BI__builtin_ia32_rndscaleps_mask:
2341 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2342 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2343 ArgNum = 4;
2344 break;
2345 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002346 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002347 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002348 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002349 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002350 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002351 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002352 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002353 case X86::BI__builtin_ia32_rangepd512_mask:
2354 case X86::BI__builtin_ia32_rangeps512_mask:
2355 case X86::BI__builtin_ia32_rangesd128_round_mask:
2356 case X86::BI__builtin_ia32_rangess128_round_mask:
2357 case X86::BI__builtin_ia32_reducesd_mask:
2358 case X86::BI__builtin_ia32_reducess_mask:
2359 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2360 case X86::BI__builtin_ia32_rndscaless_round_mask:
2361 ArgNum = 5;
2362 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002363 case X86::BI__builtin_ia32_vcvtsd2si64:
2364 case X86::BI__builtin_ia32_vcvtsd2si32:
2365 case X86::BI__builtin_ia32_vcvtsd2usi32:
2366 case X86::BI__builtin_ia32_vcvtsd2usi64:
2367 case X86::BI__builtin_ia32_vcvtss2si32:
2368 case X86::BI__builtin_ia32_vcvtss2si64:
2369 case X86::BI__builtin_ia32_vcvtss2usi32:
2370 case X86::BI__builtin_ia32_vcvtss2usi64:
2371 ArgNum = 1;
2372 HasRC = true;
2373 break;
Craig Topper3614b412018-06-10 06:01:42 +00002374 case X86::BI__builtin_ia32_addpd512:
2375 case X86::BI__builtin_ia32_addps512:
2376 case X86::BI__builtin_ia32_divpd512:
2377 case X86::BI__builtin_ia32_divps512:
2378 case X86::BI__builtin_ia32_mulpd512:
2379 case X86::BI__builtin_ia32_mulps512:
2380 case X86::BI__builtin_ia32_subpd512:
2381 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00002382 case X86::BI__builtin_ia32_cvtsi2sd64:
2383 case X86::BI__builtin_ia32_cvtsi2ss32:
2384 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002385 case X86::BI__builtin_ia32_cvtusi2sd64:
2386 case X86::BI__builtin_ia32_cvtusi2ss32:
2387 case X86::BI__builtin_ia32_cvtusi2ss64:
2388 ArgNum = 2;
2389 HasRC = true;
2390 break;
2391 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2392 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2393 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2394 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2395 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2396 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2397 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2398 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2399 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2400 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2401 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002402 case X86::BI__builtin_ia32_sqrtpd512_mask:
2403 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002404 ArgNum = 3;
2405 HasRC = true;
2406 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002407 case X86::BI__builtin_ia32_addss_round_mask:
2408 case X86::BI__builtin_ia32_addsd_round_mask:
2409 case X86::BI__builtin_ia32_divss_round_mask:
2410 case X86::BI__builtin_ia32_divsd_round_mask:
2411 case X86::BI__builtin_ia32_mulss_round_mask:
2412 case X86::BI__builtin_ia32_mulsd_round_mask:
2413 case X86::BI__builtin_ia32_subss_round_mask:
2414 case X86::BI__builtin_ia32_subsd_round_mask:
2415 case X86::BI__builtin_ia32_scalefpd512_mask:
2416 case X86::BI__builtin_ia32_scalefps512_mask:
2417 case X86::BI__builtin_ia32_scalefsd_round_mask:
2418 case X86::BI__builtin_ia32_scalefss_round_mask:
2419 case X86::BI__builtin_ia32_getmantpd512_mask:
2420 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002421 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2422 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2423 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002424 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2425 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2426 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2427 case X86::BI__builtin_ia32_vfmaddss3_mask:
2428 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2429 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00002430 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2431 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2432 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2433 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2434 case X86::BI__builtin_ia32_vfmaddps512_mask:
2435 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2436 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2437 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2438 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2439 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2440 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2441 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2442 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2443 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2444 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2445 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00002446 ArgNum = 4;
2447 HasRC = true;
2448 break;
2449 case X86::BI__builtin_ia32_getmantsd_round_mask:
2450 case X86::BI__builtin_ia32_getmantss_round_mask:
2451 ArgNum = 5;
2452 HasRC = true;
2453 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002454 }
2455
2456 llvm::APSInt Result;
2457
2458 // We can't check the value of a dependent argument.
2459 Expr *Arg = TheCall->getArg(ArgNum);
2460 if (Arg->isTypeDependent() || Arg->isValueDependent())
2461 return false;
2462
2463 // Check constant-ness first.
2464 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2465 return true;
2466
2467 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2468 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2469 // combined with ROUND_NO_EXC.
2470 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2471 Result == 8/*ROUND_NO_EXC*/ ||
2472 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2473 return false;
2474
2475 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2476 << Arg->getSourceRange();
2477}
2478
Craig Topperdf5beb22017-03-13 17:16:50 +00002479// Check if the gather/scatter scale is legal.
2480bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2481 CallExpr *TheCall) {
2482 unsigned ArgNum = 0;
2483 switch (BuiltinID) {
2484 default:
2485 return false;
2486 case X86::BI__builtin_ia32_gatherpfdpd:
2487 case X86::BI__builtin_ia32_gatherpfdps:
2488 case X86::BI__builtin_ia32_gatherpfqpd:
2489 case X86::BI__builtin_ia32_gatherpfqps:
2490 case X86::BI__builtin_ia32_scatterpfdpd:
2491 case X86::BI__builtin_ia32_scatterpfdps:
2492 case X86::BI__builtin_ia32_scatterpfqpd:
2493 case X86::BI__builtin_ia32_scatterpfqps:
2494 ArgNum = 3;
2495 break;
2496 case X86::BI__builtin_ia32_gatherd_pd:
2497 case X86::BI__builtin_ia32_gatherd_pd256:
2498 case X86::BI__builtin_ia32_gatherq_pd:
2499 case X86::BI__builtin_ia32_gatherq_pd256:
2500 case X86::BI__builtin_ia32_gatherd_ps:
2501 case X86::BI__builtin_ia32_gatherd_ps256:
2502 case X86::BI__builtin_ia32_gatherq_ps:
2503 case X86::BI__builtin_ia32_gatherq_ps256:
2504 case X86::BI__builtin_ia32_gatherd_q:
2505 case X86::BI__builtin_ia32_gatherd_q256:
2506 case X86::BI__builtin_ia32_gatherq_q:
2507 case X86::BI__builtin_ia32_gatherq_q256:
2508 case X86::BI__builtin_ia32_gatherd_d:
2509 case X86::BI__builtin_ia32_gatherd_d256:
2510 case X86::BI__builtin_ia32_gatherq_d:
2511 case X86::BI__builtin_ia32_gatherq_d256:
2512 case X86::BI__builtin_ia32_gather3div2df:
2513 case X86::BI__builtin_ia32_gather3div2di:
2514 case X86::BI__builtin_ia32_gather3div4df:
2515 case X86::BI__builtin_ia32_gather3div4di:
2516 case X86::BI__builtin_ia32_gather3div4sf:
2517 case X86::BI__builtin_ia32_gather3div4si:
2518 case X86::BI__builtin_ia32_gather3div8sf:
2519 case X86::BI__builtin_ia32_gather3div8si:
2520 case X86::BI__builtin_ia32_gather3siv2df:
2521 case X86::BI__builtin_ia32_gather3siv2di:
2522 case X86::BI__builtin_ia32_gather3siv4df:
2523 case X86::BI__builtin_ia32_gather3siv4di:
2524 case X86::BI__builtin_ia32_gather3siv4sf:
2525 case X86::BI__builtin_ia32_gather3siv4si:
2526 case X86::BI__builtin_ia32_gather3siv8sf:
2527 case X86::BI__builtin_ia32_gather3siv8si:
2528 case X86::BI__builtin_ia32_gathersiv8df:
2529 case X86::BI__builtin_ia32_gathersiv16sf:
2530 case X86::BI__builtin_ia32_gatherdiv8df:
2531 case X86::BI__builtin_ia32_gatherdiv16sf:
2532 case X86::BI__builtin_ia32_gathersiv8di:
2533 case X86::BI__builtin_ia32_gathersiv16si:
2534 case X86::BI__builtin_ia32_gatherdiv8di:
2535 case X86::BI__builtin_ia32_gatherdiv16si:
2536 case X86::BI__builtin_ia32_scatterdiv2df:
2537 case X86::BI__builtin_ia32_scatterdiv2di:
2538 case X86::BI__builtin_ia32_scatterdiv4df:
2539 case X86::BI__builtin_ia32_scatterdiv4di:
2540 case X86::BI__builtin_ia32_scatterdiv4sf:
2541 case X86::BI__builtin_ia32_scatterdiv4si:
2542 case X86::BI__builtin_ia32_scatterdiv8sf:
2543 case X86::BI__builtin_ia32_scatterdiv8si:
2544 case X86::BI__builtin_ia32_scattersiv2df:
2545 case X86::BI__builtin_ia32_scattersiv2di:
2546 case X86::BI__builtin_ia32_scattersiv4df:
2547 case X86::BI__builtin_ia32_scattersiv4di:
2548 case X86::BI__builtin_ia32_scattersiv4sf:
2549 case X86::BI__builtin_ia32_scattersiv4si:
2550 case X86::BI__builtin_ia32_scattersiv8sf:
2551 case X86::BI__builtin_ia32_scattersiv8si:
2552 case X86::BI__builtin_ia32_scattersiv8df:
2553 case X86::BI__builtin_ia32_scattersiv16sf:
2554 case X86::BI__builtin_ia32_scatterdiv8df:
2555 case X86::BI__builtin_ia32_scatterdiv16sf:
2556 case X86::BI__builtin_ia32_scattersiv8di:
2557 case X86::BI__builtin_ia32_scattersiv16si:
2558 case X86::BI__builtin_ia32_scatterdiv8di:
2559 case X86::BI__builtin_ia32_scatterdiv16si:
2560 ArgNum = 4;
2561 break;
2562 }
2563
2564 llvm::APSInt Result;
2565
2566 // We can't check the value of a dependent argument.
2567 Expr *Arg = TheCall->getArg(ArgNum);
2568 if (Arg->isTypeDependent() || Arg->isValueDependent())
2569 return false;
2570
2571 // Check constant-ness first.
2572 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2573 return true;
2574
2575 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2576 return false;
2577
2578 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2579 << Arg->getSourceRange();
2580}
2581
Craig Topper51738f82018-04-26 20:14:46 +00002582static bool isX86_32Builtin(unsigned BuiltinID) {
2583 // These builtins only work on x86-32 targets.
2584 switch (BuiltinID) {
2585 case X86::BI__builtin_ia32_readeflags_u32:
2586 case X86::BI__builtin_ia32_writeeflags_u32:
2587 return true;
2588 }
2589
2590 return false;
2591}
2592
Craig Topperf0ddc892016-09-23 04:48:27 +00002593bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2594 if (BuiltinID == X86::BI__builtin_cpu_supports)
2595 return SemaBuiltinCpuSupports(*this, TheCall);
2596
Craig Topper699ae0c2017-08-10 20:28:30 +00002597 if (BuiltinID == X86::BI__builtin_cpu_is)
2598 return SemaBuiltinCpuIs(*this, TheCall);
2599
Craig Topper51738f82018-04-26 20:14:46 +00002600 // Check for 32-bit only builtins on a 64-bit target.
2601 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2602 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2603 return Diag(TheCall->getCallee()->getLocStart(),
2604 diag::err_32_bit_builtin_64_bit_tgt);
2605
Craig Toppera7e253e2016-09-23 04:48:31 +00002606 // If the intrinsic has rounding or SAE make sure its valid.
2607 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2608 return true;
2609
Craig Topperdf5beb22017-03-13 17:16:50 +00002610 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2611 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2612 return true;
2613
Craig Topperf0ddc892016-09-23 04:48:27 +00002614 // For intrinsics which take an immediate value as part of the instruction,
2615 // range check them here.
2616 int i = 0, l = 0, u = 0;
2617 switch (BuiltinID) {
2618 default:
2619 return false;
Craig Topper11899b02018-06-05 21:54:35 +00002620 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00002621 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002622 case X86::BI__builtin_ia32_vextractf128_pd256:
2623 case X86::BI__builtin_ia32_vextractf128_ps256:
2624 case X86::BI__builtin_ia32_vextractf128_si256:
2625 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00002626 case X86::BI__builtin_ia32_extractf64x4_mask:
2627 case X86::BI__builtin_ia32_extracti64x4_mask:
2628 case X86::BI__builtin_ia32_extractf32x8_mask:
2629 case X86::BI__builtin_ia32_extracti32x8_mask:
2630 case X86::BI__builtin_ia32_extractf64x2_256_mask:
2631 case X86::BI__builtin_ia32_extracti64x2_256_mask:
2632 case X86::BI__builtin_ia32_extractf32x4_256_mask:
2633 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002634 i = 1; l = 0; u = 1;
2635 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002636 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002637 case X86::BI__builtin_ia32_vinsertf128_pd256:
2638 case X86::BI__builtin_ia32_vinsertf128_ps256:
2639 case X86::BI__builtin_ia32_vinsertf128_si256:
2640 case X86::BI__builtin_ia32_insert128i256:
2641 case X86::BI__builtin_ia32_insertf32x8:
2642 case X86::BI__builtin_ia32_inserti32x8:
2643 case X86::BI__builtin_ia32_insertf64x4:
2644 case X86::BI__builtin_ia32_inserti64x4:
2645 case X86::BI__builtin_ia32_insertf64x2_256:
2646 case X86::BI__builtin_ia32_inserti64x2_256:
2647 case X86::BI__builtin_ia32_insertf32x4_256:
2648 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00002649 i = 2; l = 0; u = 1;
2650 break;
Craig Topperacf56012018-06-08 00:59:27 +00002651 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00002652 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002653 case X86::BI__builtin_ia32_vec_ext_v4si:
2654 case X86::BI__builtin_ia32_vec_ext_v4sf:
2655 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00002656 case X86::BI__builtin_ia32_extractf32x4_mask:
2657 case X86::BI__builtin_ia32_extracti32x4_mask:
2658 case X86::BI__builtin_ia32_extractf64x2_512_mask:
2659 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002660 i = 1; l = 0; u = 3;
2661 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002662 case X86::BI_mm_prefetch:
2663 case X86::BI__builtin_ia32_vec_ext_v8hi:
2664 case X86::BI__builtin_ia32_vec_ext_v8si:
2665 i = 1; l = 0; u = 7;
2666 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002667 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00002668 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00002669 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00002670 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002671 case X86::BI__builtin_ia32_vec_set_v4si:
2672 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00002673 case X86::BI__builtin_ia32_shuf_f32x4_256:
2674 case X86::BI__builtin_ia32_shuf_f64x2_256:
2675 case X86::BI__builtin_ia32_shuf_i32x4_256:
2676 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00002677 case X86::BI__builtin_ia32_insertf64x2_512:
2678 case X86::BI__builtin_ia32_inserti64x2_512:
2679 case X86::BI__builtin_ia32_insertf32x4:
2680 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00002681 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002682 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002683 case X86::BI__builtin_ia32_vpermil2pd:
2684 case X86::BI__builtin_ia32_vpermil2pd256:
2685 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002686 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002687 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002688 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002689 case X86::BI__builtin_ia32_cmpb128_mask:
2690 case X86::BI__builtin_ia32_cmpw128_mask:
2691 case X86::BI__builtin_ia32_cmpd128_mask:
2692 case X86::BI__builtin_ia32_cmpq128_mask:
2693 case X86::BI__builtin_ia32_cmpb256_mask:
2694 case X86::BI__builtin_ia32_cmpw256_mask:
2695 case X86::BI__builtin_ia32_cmpd256_mask:
2696 case X86::BI__builtin_ia32_cmpq256_mask:
2697 case X86::BI__builtin_ia32_cmpb512_mask:
2698 case X86::BI__builtin_ia32_cmpw512_mask:
2699 case X86::BI__builtin_ia32_cmpd512_mask:
2700 case X86::BI__builtin_ia32_cmpq512_mask:
2701 case X86::BI__builtin_ia32_ucmpb128_mask:
2702 case X86::BI__builtin_ia32_ucmpw128_mask:
2703 case X86::BI__builtin_ia32_ucmpd128_mask:
2704 case X86::BI__builtin_ia32_ucmpq128_mask:
2705 case X86::BI__builtin_ia32_ucmpb256_mask:
2706 case X86::BI__builtin_ia32_ucmpw256_mask:
2707 case X86::BI__builtin_ia32_ucmpd256_mask:
2708 case X86::BI__builtin_ia32_ucmpq256_mask:
2709 case X86::BI__builtin_ia32_ucmpb512_mask:
2710 case X86::BI__builtin_ia32_ucmpw512_mask:
2711 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002712 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002713 case X86::BI__builtin_ia32_vpcomub:
2714 case X86::BI__builtin_ia32_vpcomuw:
2715 case X86::BI__builtin_ia32_vpcomud:
2716 case X86::BI__builtin_ia32_vpcomuq:
2717 case X86::BI__builtin_ia32_vpcomb:
2718 case X86::BI__builtin_ia32_vpcomw:
2719 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002720 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002721 case X86::BI__builtin_ia32_vec_set_v8hi:
2722 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002723 i = 2; l = 0; u = 7;
2724 break;
Craig Topperacf56012018-06-08 00:59:27 +00002725 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002726 case X86::BI__builtin_ia32_roundps:
2727 case X86::BI__builtin_ia32_roundpd:
2728 case X86::BI__builtin_ia32_roundps256:
2729 case X86::BI__builtin_ia32_roundpd256:
Craig Topperf3914b72018-06-06 00:24:55 +00002730 case X86::BI__builtin_ia32_vec_ext_v16qi:
2731 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002732 i = 1; l = 0; u = 15;
2733 break;
Craig Topper7d17d722018-06-08 00:00:21 +00002734 case X86::BI__builtin_ia32_pblendd128:
2735 case X86::BI__builtin_ia32_blendps:
2736 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00002737 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002738 case X86::BI__builtin_ia32_roundss:
2739 case X86::BI__builtin_ia32_roundsd:
2740 case X86::BI__builtin_ia32_rangepd128_mask:
2741 case X86::BI__builtin_ia32_rangepd256_mask:
2742 case X86::BI__builtin_ia32_rangepd512_mask:
2743 case X86::BI__builtin_ia32_rangeps128_mask:
2744 case X86::BI__builtin_ia32_rangeps256_mask:
2745 case X86::BI__builtin_ia32_rangeps512_mask:
2746 case X86::BI__builtin_ia32_getmantsd_round_mask:
2747 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002748 case X86::BI__builtin_ia32_vec_set_v16qi:
2749 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002750 i = 2; l = 0; u = 15;
2751 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002752 case X86::BI__builtin_ia32_vec_ext_v32qi:
2753 i = 1; l = 0; u = 31;
2754 break;
Craig Topper39c87102016-05-18 03:18:12 +00002755 case X86::BI__builtin_ia32_cmpps:
2756 case X86::BI__builtin_ia32_cmpss:
2757 case X86::BI__builtin_ia32_cmppd:
2758 case X86::BI__builtin_ia32_cmpsd:
2759 case X86::BI__builtin_ia32_cmpps256:
2760 case X86::BI__builtin_ia32_cmppd256:
2761 case X86::BI__builtin_ia32_cmpps128_mask:
2762 case X86::BI__builtin_ia32_cmppd128_mask:
2763 case X86::BI__builtin_ia32_cmpps256_mask:
2764 case X86::BI__builtin_ia32_cmppd256_mask:
2765 case X86::BI__builtin_ia32_cmpps512_mask:
2766 case X86::BI__builtin_ia32_cmppd512_mask:
2767 case X86::BI__builtin_ia32_cmpsd_mask:
2768 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002769 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002770 i = 2; l = 0; u = 31;
2771 break;
Craig Topper03f4f042018-06-08 18:00:25 +00002772 case X86::BI__builtin_ia32_permdf256:
2773 case X86::BI__builtin_ia32_permdi256:
2774 case X86::BI__builtin_ia32_permdf512:
2775 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00002776 case X86::BI__builtin_ia32_vpermilps:
2777 case X86::BI__builtin_ia32_vpermilps256:
2778 case X86::BI__builtin_ia32_vpermilpd512:
2779 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00002780 case X86::BI__builtin_ia32_pshufd:
2781 case X86::BI__builtin_ia32_pshufd256:
2782 case X86::BI__builtin_ia32_pshufd512:
2783 case X86::BI__builtin_ia32_pshufhw:
2784 case X86::BI__builtin_ia32_pshufhw256:
2785 case X86::BI__builtin_ia32_pshufhw512:
2786 case X86::BI__builtin_ia32_pshuflw:
2787 case X86::BI__builtin_ia32_pshuflw256:
2788 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00002789 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002790 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002791 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002792 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2793 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002794 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2795 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2796 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2797 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2798 case X86::BI__builtin_ia32_rndscaleps_mask:
2799 case X86::BI__builtin_ia32_rndscalepd_mask:
2800 case X86::BI__builtin_ia32_reducepd128_mask:
2801 case X86::BI__builtin_ia32_reducepd256_mask:
2802 case X86::BI__builtin_ia32_reducepd512_mask:
2803 case X86::BI__builtin_ia32_reduceps128_mask:
2804 case X86::BI__builtin_ia32_reduceps256_mask:
2805 case X86::BI__builtin_ia32_reduceps512_mask:
2806 case X86::BI__builtin_ia32_prold512_mask:
2807 case X86::BI__builtin_ia32_prolq512_mask:
2808 case X86::BI__builtin_ia32_prold128_mask:
2809 case X86::BI__builtin_ia32_prold256_mask:
2810 case X86::BI__builtin_ia32_prolq128_mask:
2811 case X86::BI__builtin_ia32_prolq256_mask:
2812 case X86::BI__builtin_ia32_prord128_mask:
2813 case X86::BI__builtin_ia32_prord256_mask:
2814 case X86::BI__builtin_ia32_prorq128_mask:
2815 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002816 case X86::BI__builtin_ia32_fpclasspd128_mask:
2817 case X86::BI__builtin_ia32_fpclasspd256_mask:
2818 case X86::BI__builtin_ia32_fpclassps128_mask:
2819 case X86::BI__builtin_ia32_fpclassps256_mask:
2820 case X86::BI__builtin_ia32_fpclassps512_mask:
2821 case X86::BI__builtin_ia32_fpclasspd512_mask:
2822 case X86::BI__builtin_ia32_fpclasssd_mask:
2823 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00002824 case X86::BI__builtin_ia32_pslldqi128_byteshift:
2825 case X86::BI__builtin_ia32_pslldqi256_byteshift:
2826 case X86::BI__builtin_ia32_pslldqi512_byteshift:
2827 case X86::BI__builtin_ia32_psrldqi128_byteshift:
2828 case X86::BI__builtin_ia32_psrldqi256_byteshift:
2829 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper39c87102016-05-18 03:18:12 +00002830 i = 1; l = 0; u = 255;
2831 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00002832 case X86::BI__builtin_ia32_vperm2f128_pd256:
2833 case X86::BI__builtin_ia32_vperm2f128_ps256:
2834 case X86::BI__builtin_ia32_vperm2f128_si256:
2835 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00002836 case X86::BI__builtin_ia32_pblendw128:
2837 case X86::BI__builtin_ia32_pblendw256:
2838 case X86::BI__builtin_ia32_blendps256:
2839 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00002840 case X86::BI__builtin_ia32_palignr128:
2841 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002842 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00002843 case X86::BI__builtin_ia32_alignq512:
2844 case X86::BI__builtin_ia32_alignd512:
2845 case X86::BI__builtin_ia32_alignd128:
2846 case X86::BI__builtin_ia32_alignd256:
2847 case X86::BI__builtin_ia32_alignq128:
2848 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00002849 case X86::BI__builtin_ia32_vcomisd:
2850 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00002851 case X86::BI__builtin_ia32_shuf_f32x4:
2852 case X86::BI__builtin_ia32_shuf_f64x2:
2853 case X86::BI__builtin_ia32_shuf_i32x4:
2854 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00002855 case X86::BI__builtin_ia32_shufpd512:
2856 case X86::BI__builtin_ia32_shufps:
2857 case X86::BI__builtin_ia32_shufps256:
2858 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00002859 case X86::BI__builtin_ia32_dbpsadbw128:
2860 case X86::BI__builtin_ia32_dbpsadbw256:
2861 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00002862 case X86::BI__builtin_ia32_vpshldd128:
2863 case X86::BI__builtin_ia32_vpshldd256:
2864 case X86::BI__builtin_ia32_vpshldd512:
2865 case X86::BI__builtin_ia32_vpshldq128:
2866 case X86::BI__builtin_ia32_vpshldq256:
2867 case X86::BI__builtin_ia32_vpshldq512:
2868 case X86::BI__builtin_ia32_vpshldw128:
2869 case X86::BI__builtin_ia32_vpshldw256:
2870 case X86::BI__builtin_ia32_vpshldw512:
2871 case X86::BI__builtin_ia32_vpshrdd128:
2872 case X86::BI__builtin_ia32_vpshrdd256:
2873 case X86::BI__builtin_ia32_vpshrdd512:
2874 case X86::BI__builtin_ia32_vpshrdq128:
2875 case X86::BI__builtin_ia32_vpshrdq256:
2876 case X86::BI__builtin_ia32_vpshrdq512:
2877 case X86::BI__builtin_ia32_vpshrdw128:
2878 case X86::BI__builtin_ia32_vpshrdw256:
2879 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00002880 i = 2; l = 0; u = 255;
2881 break;
2882 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2883 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2884 case X86::BI__builtin_ia32_fixupimmps512_mask:
2885 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2886 case X86::BI__builtin_ia32_fixupimmsd_mask:
2887 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2888 case X86::BI__builtin_ia32_fixupimmss_mask:
2889 case X86::BI__builtin_ia32_fixupimmss_maskz:
2890 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2891 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2892 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2893 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2894 case X86::BI__builtin_ia32_fixupimmps128_mask:
2895 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2896 case X86::BI__builtin_ia32_fixupimmps256_mask:
2897 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2898 case X86::BI__builtin_ia32_pternlogd512_mask:
2899 case X86::BI__builtin_ia32_pternlogd512_maskz:
2900 case X86::BI__builtin_ia32_pternlogq512_mask:
2901 case X86::BI__builtin_ia32_pternlogq512_maskz:
2902 case X86::BI__builtin_ia32_pternlogd128_mask:
2903 case X86::BI__builtin_ia32_pternlogd128_maskz:
2904 case X86::BI__builtin_ia32_pternlogd256_mask:
2905 case X86::BI__builtin_ia32_pternlogd256_maskz:
2906 case X86::BI__builtin_ia32_pternlogq128_mask:
2907 case X86::BI__builtin_ia32_pternlogq128_maskz:
2908 case X86::BI__builtin_ia32_pternlogq256_mask:
2909 case X86::BI__builtin_ia32_pternlogq256_maskz:
2910 i = 3; l = 0; u = 255;
2911 break;
Craig Topper9625db02017-03-12 22:19:10 +00002912 case X86::BI__builtin_ia32_gatherpfdpd:
2913 case X86::BI__builtin_ia32_gatherpfdps:
2914 case X86::BI__builtin_ia32_gatherpfqpd:
2915 case X86::BI__builtin_ia32_gatherpfqps:
2916 case X86::BI__builtin_ia32_scatterpfdpd:
2917 case X86::BI__builtin_ia32_scatterpfdps:
2918 case X86::BI__builtin_ia32_scatterpfqpd:
2919 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002920 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002921 break;
Craig Topper39c87102016-05-18 03:18:12 +00002922 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2923 case X86::BI__builtin_ia32_rndscaless_round_mask:
2924 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002925 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002926 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002927 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002928}
2929
Richard Smith55ce3522012-06-25 20:30:08 +00002930/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2931/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2932/// Returns true when the format fits the function and the FormatStringInfo has
2933/// been populated.
2934bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2935 FormatStringInfo *FSI) {
2936 FSI->HasVAListArg = Format->getFirstArg() == 0;
2937 FSI->FormatIdx = Format->getFormatIdx() - 1;
2938 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002939
Richard Smith55ce3522012-06-25 20:30:08 +00002940 // The way the format attribute works in GCC, the implicit this argument
2941 // of member functions is counted. However, it doesn't appear in our own
2942 // lists, so decrement format_idx in that case.
2943 if (IsCXXMember) {
2944 if(FSI->FormatIdx == 0)
2945 return false;
2946 --FSI->FormatIdx;
2947 if (FSI->FirstDataArg != 0)
2948 --FSI->FirstDataArg;
2949 }
2950 return true;
2951}
Mike Stump11289f42009-09-09 15:08:12 +00002952
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002953/// Checks if a the given expression evaluates to null.
2954///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002955/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002956static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002957 // If the expression has non-null type, it doesn't evaluate to null.
2958 if (auto nullability
2959 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2960 if (*nullability == NullabilityKind::NonNull)
2961 return false;
2962 }
2963
Ted Kremeneka146db32014-01-17 06:24:47 +00002964 // As a special case, transparent unions initialized with zero are
2965 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002966 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002967 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2968 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002969 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002970 if (const InitListExpr *ILE =
2971 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002972 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002973 }
2974
2975 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002976 return (!Expr->isValueDependent() &&
2977 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2978 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002979}
2980
2981static void CheckNonNullArgument(Sema &S,
2982 const Expr *ArgExpr,
2983 SourceLocation CallSiteLoc) {
2984 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002985 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2986 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002987}
2988
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002989bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2990 FormatStringInfo FSI;
2991 if ((GetFormatStringType(Format) == FST_NSString) &&
2992 getFormatStringInfo(Format, false, &FSI)) {
2993 Idx = FSI.FormatIdx;
2994 return true;
2995 }
2996 return false;
2997}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002998
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002999/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003000/// as formatting string to formatting method.
3001static void
3002DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3003 const NamedDecl *FDecl,
3004 Expr **Args,
3005 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003006 unsigned Idx = 0;
3007 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003008 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3009 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003010 Idx = 2;
3011 Format = true;
3012 }
3013 else
3014 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3015 if (S.GetFormatNSStringIdx(I, Idx)) {
3016 Format = true;
3017 break;
3018 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003019 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003020 if (!Format || NumArgs <= Idx)
3021 return;
3022 const Expr *FormatExpr = Args[Idx];
3023 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3024 FormatExpr = CSCE->getSubExpr();
3025 const StringLiteral *FormatString;
3026 if (const ObjCStringLiteral *OSL =
3027 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3028 FormatString = OSL->getString();
3029 else
3030 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3031 if (!FormatString)
3032 return;
3033 if (S.FormatStringHasSArg(FormatString)) {
3034 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3035 << "%s" << 1 << 1;
3036 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3037 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003038 }
3039}
3040
Douglas Gregorb4866e82015-06-19 18:13:19 +00003041/// Determine whether the given type has a non-null nullability annotation.
3042static bool isNonNullType(ASTContext &ctx, QualType type) {
3043 if (auto nullability = type->getNullability(ctx))
3044 return *nullability == NullabilityKind::NonNull;
3045
3046 return false;
3047}
3048
Ted Kremenek2bc73332014-01-17 06:24:43 +00003049static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00003050 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003051 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00003052 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00003053 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003054 assert((FDecl || Proto) && "Need a function declaration or prototype");
3055
Ted Kremenek9aedc152014-01-17 06:24:56 +00003056 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00003057 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00003058 if (FDecl) {
3059 // Handle the nonnull attribute on the function/method declaration itself.
3060 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3061 if (!NonNull->args_size()) {
3062 // Easy case: all pointer arguments are nonnull.
3063 for (const auto *Arg : Args)
3064 if (S.isValidPointerAttrType(Arg->getType()))
3065 CheckNonNullArgument(S, Arg, CallSiteLoc);
3066 return;
3067 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003068
Joel E. Denny81508102018-03-13 14:51:22 +00003069 for (const ParamIdx &Idx : NonNull->args()) {
3070 unsigned IdxAST = Idx.getASTIndex();
3071 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00003072 continue;
3073 if (NonNullArgs.empty())
3074 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00003075 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003076 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003077 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003078 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003079
Douglas Gregorb4866e82015-06-19 18:13:19 +00003080 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3081 // Handle the nonnull attribute on the parameters of the
3082 // function/method.
3083 ArrayRef<ParmVarDecl*> parms;
3084 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3085 parms = FD->parameters();
3086 else
3087 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3088
3089 unsigned ParamIndex = 0;
3090 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3091 I != E; ++I, ++ParamIndex) {
3092 const ParmVarDecl *PVD = *I;
3093 if (PVD->hasAttr<NonNullAttr>() ||
3094 isNonNullType(S.Context, PVD->getType())) {
3095 if (NonNullArgs.empty())
3096 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00003097
Douglas Gregorb4866e82015-06-19 18:13:19 +00003098 NonNullArgs.set(ParamIndex);
3099 }
3100 }
3101 } else {
3102 // If we have a non-function, non-method declaration but no
3103 // function prototype, try to dig out the function prototype.
3104 if (!Proto) {
3105 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3106 QualType type = VD->getType().getNonReferenceType();
3107 if (auto pointerType = type->getAs<PointerType>())
3108 type = pointerType->getPointeeType();
3109 else if (auto blockType = type->getAs<BlockPointerType>())
3110 type = blockType->getPointeeType();
3111 // FIXME: data member pointers?
3112
3113 // Dig out the function prototype, if there is one.
3114 Proto = type->getAs<FunctionProtoType>();
3115 }
3116 }
3117
3118 // Fill in non-null argument information from the nullability
3119 // information on the parameter types (if we have them).
3120 if (Proto) {
3121 unsigned Index = 0;
3122 for (auto paramType : Proto->getParamTypes()) {
3123 if (isNonNullType(S.Context, paramType)) {
3124 if (NonNullArgs.empty())
3125 NonNullArgs.resize(Args.size());
3126
3127 NonNullArgs.set(Index);
3128 }
3129
3130 ++Index;
3131 }
3132 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003133 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003134
Douglas Gregorb4866e82015-06-19 18:13:19 +00003135 // Check for non-null arguments.
3136 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3137 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00003138 if (NonNullArgs[ArgIndex])
3139 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003140 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003141}
3142
Richard Smith55ce3522012-06-25 20:30:08 +00003143/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00003144/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3145/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003146void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00003147 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3148 bool IsMemberFunction, SourceLocation Loc,
3149 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00003150 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00003151 if (CurContext->isDependentContext())
3152 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00003153
Ted Kremenekb8176da2010-09-09 04:33:05 +00003154 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003155 llvm::SmallBitVector CheckedVarArgs;
3156 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003157 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003158 // Only create vector if there are format attributes.
3159 CheckedVarArgs.resize(Args.size());
3160
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003161 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003162 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003163 }
Richard Smithd7293d72013-08-05 18:49:43 +00003164 }
Richard Smith55ce3522012-06-25 20:30:08 +00003165
3166 // Refuse POD arguments that weren't caught by the format string
3167 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003168 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3169 if (CallType != VariadicDoesNotApply &&
3170 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003171 unsigned NumParams = Proto ? Proto->getNumParams()
3172 : FDecl && isa<FunctionDecl>(FDecl)
3173 ? cast<FunctionDecl>(FDecl)->getNumParams()
3174 : FDecl && isa<ObjCMethodDecl>(FDecl)
3175 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3176 : 0;
3177
Alp Toker9cacbab2014-01-20 20:26:09 +00003178 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003179 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003180 if (const Expr *Arg = Args[ArgIdx]) {
3181 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3182 checkVariadicArgument(Arg, CallType);
3183 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003184 }
Richard Smithd7293d72013-08-05 18:49:43 +00003185 }
Mike Stump11289f42009-09-09 15:08:12 +00003186
Douglas Gregorb4866e82015-06-19 18:13:19 +00003187 if (FDecl || Proto) {
3188 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003189
Richard Trieu41bc0992013-06-22 00:20:41 +00003190 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003191 if (FDecl) {
3192 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003193 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003194 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003195 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003196
3197 if (FD)
3198 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003199}
3200
3201/// CheckConstructorCall - Check a constructor call for correctness and safety
3202/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003203void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3204 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003205 const FunctionProtoType *Proto,
3206 SourceLocation Loc) {
3207 VariadicCallType CallType =
3208 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003209 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3210 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003211}
3212
3213/// CheckFunctionCall - Check a direct function call for various correctness
3214/// and safety properties not strictly enforced by the C type system.
3215bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3216 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003217 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3218 isa<CXXMethodDecl>(FDecl);
3219 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3220 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003221 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3222 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003223 Expr** Args = TheCall->getArgs();
3224 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003225
3226 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003227 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003228 // If this is a call to a member operator, hide the first argument
3229 // from checkCall.
3230 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003231 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003232 ++Args;
3233 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003234 } else if (IsMemberFunction)
3235 ImplicitThis =
3236 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3237
3238 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003239 IsMemberFunction, TheCall->getRParenLoc(),
3240 TheCall->getCallee()->getSourceRange(), CallType);
3241
3242 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3243 // None of the checks below are needed for functions that don't have
3244 // simple names (e.g., C++ conversion functions).
3245 if (!FnInfo)
3246 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003247
Richard Trieua7f30b12016-12-06 01:42:28 +00003248 CheckAbsoluteValueFunction(TheCall, FDecl);
3249 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003250
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003251 if (getLangOpts().ObjC1)
3252 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003253
Anna Zaks22122702012-01-17 00:37:07 +00003254 unsigned CMId = FDecl->getMemoryFunctionKind();
3255 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003256 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003257
Anna Zaks201d4892012-01-13 21:52:01 +00003258 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003259 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003260 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003261 else if (CMId == Builtin::BIstrncat)
3262 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003263 else
Anna Zaks22122702012-01-17 00:37:07 +00003264 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003265
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003266 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003267}
3268
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003269bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003270 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003271 VariadicCallType CallType =
3272 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003273
George Burgess IVce6284b2017-01-28 02:19:40 +00003274 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3275 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003276 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003277
3278 return false;
3279}
3280
Richard Trieu664c4c62013-06-20 21:03:13 +00003281bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3282 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003283 QualType Ty;
3284 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003285 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003286 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003287 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003288 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003289 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003290
Douglas Gregorb4866e82015-06-19 18:13:19 +00003291 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3292 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003293 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003294
Richard Trieu664c4c62013-06-20 21:03:13 +00003295 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003296 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003297 CallType = VariadicDoesNotApply;
3298 } else if (Ty->isBlockPointerType()) {
3299 CallType = VariadicBlock;
3300 } else { // Ty->isFunctionPointerType()
3301 CallType = VariadicFunction;
3302 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003303
George Burgess IVce6284b2017-01-28 02:19:40 +00003304 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003305 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3306 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003307 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003308
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003309 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003310}
3311
Richard Trieu41bc0992013-06-22 00:20:41 +00003312/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3313/// such as function pointers returned from functions.
3314bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003315 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003316 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003317 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003318 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003319 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003320 TheCall->getCallee()->getSourceRange(), CallType);
3321
3322 return false;
3323}
3324
Tim Northovere94a34c2014-03-11 10:49:14 +00003325static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003326 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003327 return false;
3328
JF Bastiendda2cb12016-04-18 18:01:49 +00003329 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003330 switch (Op) {
3331 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003332 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003333 llvm_unreachable("There is no ordering argument for an init");
3334
3335 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003336 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003337 case AtomicExpr::AO__atomic_load_n:
3338 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003339 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3340 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003341
3342 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003343 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003344 case AtomicExpr::AO__atomic_store:
3345 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003346 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3347 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3348 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003349
3350 default:
3351 return true;
3352 }
3353}
3354
Richard Smithfeea8832012-04-12 05:08:17 +00003355ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3356 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003357 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3358 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003359
Yaxun Liu39195062017-08-04 18:16:31 +00003360 // All the non-OpenCL operations take one of the following forms.
3361 // The OpenCL operations take the __c11 forms with one extra argument for
3362 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003363 enum {
3364 // C __c11_atomic_init(A *, C)
3365 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003366
Richard Smithfeea8832012-04-12 05:08:17 +00003367 // C __c11_atomic_load(A *, int)
3368 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003369
Richard Smithfeea8832012-04-12 05:08:17 +00003370 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003371 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003372
Eric Fiselier8d662442016-03-30 23:39:56 +00003373 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003374 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003375
Richard Smithfeea8832012-04-12 05:08:17 +00003376 // C __c11_atomic_add(A *, M, int)
3377 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003378
Richard Smithfeea8832012-04-12 05:08:17 +00003379 // C __atomic_exchange_n(A *, CP, int)
3380 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003381
Richard Smithfeea8832012-04-12 05:08:17 +00003382 // void __atomic_exchange(A *, C *, CP, int)
3383 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003384
Richard Smithfeea8832012-04-12 05:08:17 +00003385 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3386 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003387
Richard Smithfeea8832012-04-12 05:08:17 +00003388 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3389 GNUCmpXchg
3390 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003391
Yaxun Liu39195062017-08-04 18:16:31 +00003392 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003393 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3394 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003395 // where:
3396 // C is an appropriate type,
3397 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3398 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3399 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3400 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003401
Yaxun Liu39195062017-08-04 18:16:31 +00003402 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3403 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3404 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003405 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3406 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3407 AtomicExpr::AO__atomic_load,
3408 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003409 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3410 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3411 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3412 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3413 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003414 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3415 Op == AtomicExpr::AO__atomic_store_n ||
3416 Op == AtomicExpr::AO__atomic_exchange_n ||
3417 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3418 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003419 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003420
3421 switch (Op) {
3422 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003423 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003424 Form = Init;
3425 break;
3426
3427 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003428 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003429 case AtomicExpr::AO__atomic_load_n:
3430 Form = Load;
3431 break;
3432
Richard Smithfeea8832012-04-12 05:08:17 +00003433 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003434 Form = LoadCopy;
3435 break;
3436
3437 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003438 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003439 case AtomicExpr::AO__atomic_store:
3440 case AtomicExpr::AO__atomic_store_n:
3441 Form = Copy;
3442 break;
3443
3444 case AtomicExpr::AO__c11_atomic_fetch_add:
3445 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003446 case AtomicExpr::AO__opencl_atomic_fetch_add:
3447 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3448 case AtomicExpr::AO__opencl_atomic_fetch_min:
3449 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003450 case AtomicExpr::AO__atomic_fetch_add:
3451 case AtomicExpr::AO__atomic_fetch_sub:
3452 case AtomicExpr::AO__atomic_add_fetch:
3453 case AtomicExpr::AO__atomic_sub_fetch:
3454 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003455 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003456 case AtomicExpr::AO__c11_atomic_fetch_and:
3457 case AtomicExpr::AO__c11_atomic_fetch_or:
3458 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003459 case AtomicExpr::AO__opencl_atomic_fetch_and:
3460 case AtomicExpr::AO__opencl_atomic_fetch_or:
3461 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003462 case AtomicExpr::AO__atomic_fetch_and:
3463 case AtomicExpr::AO__atomic_fetch_or:
3464 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003465 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003466 case AtomicExpr::AO__atomic_and_fetch:
3467 case AtomicExpr::AO__atomic_or_fetch:
3468 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003469 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003470 Form = Arithmetic;
3471 break;
3472
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003473 case AtomicExpr::AO__atomic_fetch_min:
3474 case AtomicExpr::AO__atomic_fetch_max:
3475 IsMinMax = true;
3476 Form = Arithmetic;
3477 break;
3478
Richard Smithfeea8832012-04-12 05:08:17 +00003479 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003480 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003481 case AtomicExpr::AO__atomic_exchange_n:
3482 Form = Xchg;
3483 break;
3484
3485 case AtomicExpr::AO__atomic_exchange:
3486 Form = GNUXchg;
3487 break;
3488
3489 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3490 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003491 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3492 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003493 Form = C11CmpXchg;
3494 break;
3495
3496 case AtomicExpr::AO__atomic_compare_exchange:
3497 case AtomicExpr::AO__atomic_compare_exchange_n:
3498 Form = GNUCmpXchg;
3499 break;
3500 }
3501
Yaxun Liu39195062017-08-04 18:16:31 +00003502 unsigned AdjustedNumArgs = NumArgs[Form];
3503 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3504 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003505 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003506 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003507 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003508 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003509 << TheCall->getCallee()->getSourceRange();
3510 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003511 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3512 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003513 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003514 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003515 << TheCall->getCallee()->getSourceRange();
3516 return ExprError();
3517 }
3518
Richard Smithfeea8832012-04-12 05:08:17 +00003519 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003520 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003521 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3522 if (ConvertedPtr.isInvalid())
3523 return ExprError();
3524
3525 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003526 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3527 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003528 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003529 << Ptr->getType() << Ptr->getSourceRange();
3530 return ExprError();
3531 }
3532
Richard Smithfeea8832012-04-12 05:08:17 +00003533 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3534 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3535 QualType ValType = AtomTy; // 'C'
3536 if (IsC11) {
3537 if (!AtomTy->isAtomicType()) {
3538 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3539 << Ptr->getType() << Ptr->getSourceRange();
3540 return ExprError();
3541 }
Yaxun Liu39195062017-08-04 18:16:31 +00003542 if (AtomTy.isConstQualified() ||
3543 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003544 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003545 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3546 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003547 return ExprError();
3548 }
Richard Smithfeea8832012-04-12 05:08:17 +00003549 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003550 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003551 if (ValType.isConstQualified()) {
3552 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3553 << Ptr->getType() << Ptr->getSourceRange();
3554 return ExprError();
3555 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003556 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003557
Richard Smithfeea8832012-04-12 05:08:17 +00003558 // For an arithmetic operation, the implied arithmetic must be well-formed.
3559 if (Form == Arithmetic) {
3560 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003561 if (IsAddSub && !ValType->isIntegerType()
3562 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003563 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3564 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3565 return ExprError();
3566 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003567 if (IsMinMax) {
3568 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3569 if (!BT || (BT->getKind() != BuiltinType::Int &&
3570 BT->getKind() != BuiltinType::UInt)) {
3571 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3572 return ExprError();
3573 }
3574 }
3575 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003576 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3577 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3578 return ExprError();
3579 }
David Majnemere85cff82015-01-28 05:48:06 +00003580 if (IsC11 && ValType->isPointerType() &&
3581 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3582 diag::err_incomplete_type)) {
3583 return ExprError();
3584 }
Richard Smithfeea8832012-04-12 05:08:17 +00003585 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3586 // For __atomic_*_n operations, the value type must be a scalar integral or
3587 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003588 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003589 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3590 return ExprError();
3591 }
3592
Eli Friedmanaa769812013-09-11 03:49:34 +00003593 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3594 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003595 // For GNU atomics, require a trivially-copyable type. This is not part of
3596 // the GNU atomics specification, but we enforce it for sanity.
3597 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003598 << Ptr->getType() << Ptr->getSourceRange();
3599 return ExprError();
3600 }
3601
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003602 switch (ValType.getObjCLifetime()) {
3603 case Qualifiers::OCL_None:
3604 case Qualifiers::OCL_ExplicitNone:
3605 // okay
3606 break;
3607
3608 case Qualifiers::OCL_Weak:
3609 case Qualifiers::OCL_Strong:
3610 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003611 // FIXME: Can this happen? By this point, ValType should be known
3612 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003613 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3614 << ValType << Ptr->getSourceRange();
3615 return ExprError();
3616 }
3617
JF Bastien7f0a05a2018-05-25 00:07:09 +00003618 // All atomic operations have an overload which takes a pointer to a volatile
3619 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3620 // into the result or the other operands. Similarly atomic_load takes a
3621 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003622 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003623 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003624 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003625 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3626 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003627 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003628 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003629 ResultType = Context.BoolTy;
3630
Richard Smithfeea8832012-04-12 05:08:17 +00003631 // The type of a parameter passed 'by value'. In the GNU atomics, such
3632 // arguments are actually passed as pointers.
3633 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003634 bool IsPassedByAddress = false;
3635 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003636 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003637 IsPassedByAddress = true;
3638 }
Richard Smithfeea8832012-04-12 05:08:17 +00003639
JF Bastien7f0a05a2018-05-25 00:07:09 +00003640 // The first argument's non-CV pointer type is used to deduce the type of
3641 // subsequent arguments, except for:
3642 // - weak flag (always converted to bool)
3643 // - memory order (always converted to int)
3644 // - scope (always converted to int)
3645 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003646 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003647 if (i < NumVals[Form] + 1) {
3648 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003649 case 0:
3650 // The first argument is always a pointer. It has a fixed type.
3651 // It is always dereferenced, a nullptr is undefined.
3652 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3653 // Nothing else to do: we already know all we want about this pointer.
3654 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003655 case 1:
3656 // The second argument is the non-atomic operand. For arithmetic, this
3657 // is always passed by value, and for a compare_exchange it is always
3658 // passed by address. For the rest, GNU uses by-address and C11 uses
3659 // by-value.
3660 assert(Form != Load);
3661 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3662 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003663 else if (Form == Copy || Form == Xchg) {
3664 if (IsPassedByAddress)
3665 // The value pointer is always dereferenced, a nullptr is undefined.
3666 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003667 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003668 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003669 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003670 else {
3671 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003672 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003673 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003674 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003675 // Keep address space of non-atomic pointer type.
3676 if (const PointerType *PtrTy =
3677 ValArg->getType()->getAs<PointerType>()) {
3678 AS = PtrTy->getPointeeType().getAddressSpace();
3679 }
3680 Ty = Context.getPointerType(
3681 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3682 }
Richard Smithfeea8832012-04-12 05:08:17 +00003683 break;
3684 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003685 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003686 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3687 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003688 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003689 Ty = ByValType;
3690 break;
3691 case 3:
3692 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3693 Ty = Context.BoolTy;
3694 break;
3695 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003696 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003697 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003698 Ty = Context.IntTy;
3699 }
Richard Smithfeea8832012-04-12 05:08:17 +00003700
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003701 InitializedEntity Entity =
3702 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003703 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003704 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3705 if (Arg.isInvalid())
3706 return true;
3707 TheCall->setArg(i, Arg.get());
3708 }
3709
Richard Smithfeea8832012-04-12 05:08:17 +00003710 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003711 SmallVector<Expr*, 5> SubExprs;
3712 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003713 switch (Form) {
3714 case Init:
3715 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003716 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003717 break;
3718 case Load:
3719 SubExprs.push_back(TheCall->getArg(1)); // Order
3720 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003721 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003722 case Copy:
3723 case Arithmetic:
3724 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003725 SubExprs.push_back(TheCall->getArg(2)); // Order
3726 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003727 break;
3728 case GNUXchg:
3729 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3730 SubExprs.push_back(TheCall->getArg(3)); // Order
3731 SubExprs.push_back(TheCall->getArg(1)); // Val1
3732 SubExprs.push_back(TheCall->getArg(2)); // Val2
3733 break;
3734 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003735 SubExprs.push_back(TheCall->getArg(3)); // Order
3736 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003737 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003738 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003739 break;
3740 case GNUCmpXchg:
3741 SubExprs.push_back(TheCall->getArg(4)); // Order
3742 SubExprs.push_back(TheCall->getArg(1)); // Val1
3743 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3744 SubExprs.push_back(TheCall->getArg(2)); // Val2
3745 SubExprs.push_back(TheCall->getArg(3)); // Weak
3746 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003747 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003748
3749 if (SubExprs.size() >= 2 && Form != Init) {
3750 llvm::APSInt Result(32);
3751 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3752 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003753 Diag(SubExprs[1]->getLocStart(),
3754 diag::warn_atomic_op_has_invalid_memory_order)
3755 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003756 }
3757
Yaxun Liu30d652a2017-08-15 16:02:49 +00003758 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3759 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3760 llvm::APSInt Result(32);
3761 if (Scope->isIntegerConstantExpr(Result, Context) &&
3762 !ScopeModel->isValid(Result.getZExtValue())) {
3763 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3764 << Scope->getSourceRange();
3765 }
3766 SubExprs.push_back(Scope);
3767 }
3768
Fariborz Jahanian615de762013-05-28 17:37:39 +00003769 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3770 SubExprs, ResultType, Op,
3771 TheCall->getRParenLoc());
3772
3773 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003774 Op == AtomicExpr::AO__c11_atomic_store ||
3775 Op == AtomicExpr::AO__opencl_atomic_load ||
3776 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003777 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003778 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3779 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3780 Op == AtomicExpr::AO__opencl_atomic_load)
3781 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003782
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003783 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003784}
3785
John McCall29ad95b2011-08-27 01:09:30 +00003786/// checkBuiltinArgument - Given a call to a builtin function, perform
3787/// normal type-checking on the given argument, updating the call in
3788/// place. This is useful when a builtin function requires custom
3789/// type-checking for some of its arguments but not necessarily all of
3790/// them.
3791///
3792/// Returns true on error.
3793static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3794 FunctionDecl *Fn = E->getDirectCallee();
3795 assert(Fn && "builtin call without direct callee!");
3796
3797 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3798 InitializedEntity Entity =
3799 InitializedEntity::InitializeParameter(S.Context, Param);
3800
3801 ExprResult Arg = E->getArg(0);
3802 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3803 if (Arg.isInvalid())
3804 return true;
3805
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003806 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003807 return false;
3808}
3809
Chris Lattnerdc046542009-05-08 06:58:22 +00003810/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3811/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3812/// type of its first argument. The main ActOnCallExpr routines have already
3813/// promoted the types of arguments because all of these calls are prototyped as
3814/// void(...).
3815///
3816/// This function goes through and does final semantic checking for these
3817/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003818ExprResult
3819Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003820 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003821 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3822 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3823
3824 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003825 if (TheCall->getNumArgs() < 1) {
3826 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3827 << 0 << 1 << TheCall->getNumArgs()
3828 << TheCall->getCallee()->getSourceRange();
3829 return ExprError();
3830 }
Mike Stump11289f42009-09-09 15:08:12 +00003831
Chris Lattnerdc046542009-05-08 06:58:22 +00003832 // Inspect the first argument of the atomic builtin. This should always be
3833 // a pointer type, whose element is an integral scalar or pointer type.
3834 // Because it is a pointer type, we don't have to worry about any implicit
3835 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003836 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003837 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003838 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3839 if (FirstArgResult.isInvalid())
3840 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003841 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003842 TheCall->setArg(0, FirstArg);
3843
John McCall31168b02011-06-15 23:02:42 +00003844 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3845 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003846 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3847 << FirstArg->getType() << FirstArg->getSourceRange();
3848 return ExprError();
3849 }
Mike Stump11289f42009-09-09 15:08:12 +00003850
John McCall31168b02011-06-15 23:02:42 +00003851 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003852 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003853 !ValType->isBlockPointerType()) {
3854 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3855 << FirstArg->getType() << FirstArg->getSourceRange();
3856 return ExprError();
3857 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003858
Aaron Ballmana383c942018-05-05 17:38:42 +00003859 if (ValType.isConstQualified()) {
3860 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3861 << FirstArg->getType() << FirstArg->getSourceRange();
3862 return ExprError();
3863 }
3864
John McCall31168b02011-06-15 23:02:42 +00003865 switch (ValType.getObjCLifetime()) {
3866 case Qualifiers::OCL_None:
3867 case Qualifiers::OCL_ExplicitNone:
3868 // okay
3869 break;
3870
3871 case Qualifiers::OCL_Weak:
3872 case Qualifiers::OCL_Strong:
3873 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003874 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003875 << ValType << FirstArg->getSourceRange();
3876 return ExprError();
3877 }
3878
John McCallb50451a2011-10-05 07:41:44 +00003879 // Strip any qualifiers off ValType.
3880 ValType = ValType.getUnqualifiedType();
3881
Chandler Carruth3973af72010-07-18 20:54:12 +00003882 // The majority of builtins return a value, but a few have special return
3883 // types, so allow them to override appropriately below.
3884 QualType ResultType = ValType;
3885
Chris Lattnerdc046542009-05-08 06:58:22 +00003886 // We need to figure out which concrete builtin this maps onto. For example,
3887 // __sync_fetch_and_add with a 2 byte object turns into
3888 // __sync_fetch_and_add_2.
3889#define BUILTIN_ROW(x) \
3890 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3891 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003892
Chris Lattnerdc046542009-05-08 06:58:22 +00003893 static const unsigned BuiltinIndices[][5] = {
3894 BUILTIN_ROW(__sync_fetch_and_add),
3895 BUILTIN_ROW(__sync_fetch_and_sub),
3896 BUILTIN_ROW(__sync_fetch_and_or),
3897 BUILTIN_ROW(__sync_fetch_and_and),
3898 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003899 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003900
Chris Lattnerdc046542009-05-08 06:58:22 +00003901 BUILTIN_ROW(__sync_add_and_fetch),
3902 BUILTIN_ROW(__sync_sub_and_fetch),
3903 BUILTIN_ROW(__sync_and_and_fetch),
3904 BUILTIN_ROW(__sync_or_and_fetch),
3905 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003906 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003907
Chris Lattnerdc046542009-05-08 06:58:22 +00003908 BUILTIN_ROW(__sync_val_compare_and_swap),
3909 BUILTIN_ROW(__sync_bool_compare_and_swap),
3910 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003911 BUILTIN_ROW(__sync_lock_release),
3912 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003913 };
Mike Stump11289f42009-09-09 15:08:12 +00003914#undef BUILTIN_ROW
3915
Chris Lattnerdc046542009-05-08 06:58:22 +00003916 // Determine the index of the size.
3917 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003918 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003919 case 1: SizeIndex = 0; break;
3920 case 2: SizeIndex = 1; break;
3921 case 4: SizeIndex = 2; break;
3922 case 8: SizeIndex = 3; break;
3923 case 16: SizeIndex = 4; break;
3924 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003925 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3926 << FirstArg->getType() << FirstArg->getSourceRange();
3927 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003928 }
Mike Stump11289f42009-09-09 15:08:12 +00003929
Chris Lattnerdc046542009-05-08 06:58:22 +00003930 // Each of these builtins has one pointer argument, followed by some number of
3931 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3932 // that we ignore. Find out which row of BuiltinIndices to read from as well
3933 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003934 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003935 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003936 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003937 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003938 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003939 case Builtin::BI__sync_fetch_and_add:
3940 case Builtin::BI__sync_fetch_and_add_1:
3941 case Builtin::BI__sync_fetch_and_add_2:
3942 case Builtin::BI__sync_fetch_and_add_4:
3943 case Builtin::BI__sync_fetch_and_add_8:
3944 case Builtin::BI__sync_fetch_and_add_16:
3945 BuiltinIndex = 0;
3946 break;
3947
3948 case Builtin::BI__sync_fetch_and_sub:
3949 case Builtin::BI__sync_fetch_and_sub_1:
3950 case Builtin::BI__sync_fetch_and_sub_2:
3951 case Builtin::BI__sync_fetch_and_sub_4:
3952 case Builtin::BI__sync_fetch_and_sub_8:
3953 case Builtin::BI__sync_fetch_and_sub_16:
3954 BuiltinIndex = 1;
3955 break;
3956
3957 case Builtin::BI__sync_fetch_and_or:
3958 case Builtin::BI__sync_fetch_and_or_1:
3959 case Builtin::BI__sync_fetch_and_or_2:
3960 case Builtin::BI__sync_fetch_and_or_4:
3961 case Builtin::BI__sync_fetch_and_or_8:
3962 case Builtin::BI__sync_fetch_and_or_16:
3963 BuiltinIndex = 2;
3964 break;
3965
3966 case Builtin::BI__sync_fetch_and_and:
3967 case Builtin::BI__sync_fetch_and_and_1:
3968 case Builtin::BI__sync_fetch_and_and_2:
3969 case Builtin::BI__sync_fetch_and_and_4:
3970 case Builtin::BI__sync_fetch_and_and_8:
3971 case Builtin::BI__sync_fetch_and_and_16:
3972 BuiltinIndex = 3;
3973 break;
Mike Stump11289f42009-09-09 15:08:12 +00003974
Douglas Gregor73722482011-11-28 16:30:08 +00003975 case Builtin::BI__sync_fetch_and_xor:
3976 case Builtin::BI__sync_fetch_and_xor_1:
3977 case Builtin::BI__sync_fetch_and_xor_2:
3978 case Builtin::BI__sync_fetch_and_xor_4:
3979 case Builtin::BI__sync_fetch_and_xor_8:
3980 case Builtin::BI__sync_fetch_and_xor_16:
3981 BuiltinIndex = 4;
3982 break;
3983
Hal Finkeld2208b52014-10-02 20:53:50 +00003984 case Builtin::BI__sync_fetch_and_nand:
3985 case Builtin::BI__sync_fetch_and_nand_1:
3986 case Builtin::BI__sync_fetch_and_nand_2:
3987 case Builtin::BI__sync_fetch_and_nand_4:
3988 case Builtin::BI__sync_fetch_and_nand_8:
3989 case Builtin::BI__sync_fetch_and_nand_16:
3990 BuiltinIndex = 5;
3991 WarnAboutSemanticsChange = true;
3992 break;
3993
Douglas Gregor73722482011-11-28 16:30:08 +00003994 case Builtin::BI__sync_add_and_fetch:
3995 case Builtin::BI__sync_add_and_fetch_1:
3996 case Builtin::BI__sync_add_and_fetch_2:
3997 case Builtin::BI__sync_add_and_fetch_4:
3998 case Builtin::BI__sync_add_and_fetch_8:
3999 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004000 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00004001 break;
4002
4003 case Builtin::BI__sync_sub_and_fetch:
4004 case Builtin::BI__sync_sub_and_fetch_1:
4005 case Builtin::BI__sync_sub_and_fetch_2:
4006 case Builtin::BI__sync_sub_and_fetch_4:
4007 case Builtin::BI__sync_sub_and_fetch_8:
4008 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004009 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00004010 break;
4011
4012 case Builtin::BI__sync_and_and_fetch:
4013 case Builtin::BI__sync_and_and_fetch_1:
4014 case Builtin::BI__sync_and_and_fetch_2:
4015 case Builtin::BI__sync_and_and_fetch_4:
4016 case Builtin::BI__sync_and_and_fetch_8:
4017 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004018 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00004019 break;
4020
4021 case Builtin::BI__sync_or_and_fetch:
4022 case Builtin::BI__sync_or_and_fetch_1:
4023 case Builtin::BI__sync_or_and_fetch_2:
4024 case Builtin::BI__sync_or_and_fetch_4:
4025 case Builtin::BI__sync_or_and_fetch_8:
4026 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004027 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00004028 break;
4029
4030 case Builtin::BI__sync_xor_and_fetch:
4031 case Builtin::BI__sync_xor_and_fetch_1:
4032 case Builtin::BI__sync_xor_and_fetch_2:
4033 case Builtin::BI__sync_xor_and_fetch_4:
4034 case Builtin::BI__sync_xor_and_fetch_8:
4035 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004036 BuiltinIndex = 10;
4037 break;
4038
4039 case Builtin::BI__sync_nand_and_fetch:
4040 case Builtin::BI__sync_nand_and_fetch_1:
4041 case Builtin::BI__sync_nand_and_fetch_2:
4042 case Builtin::BI__sync_nand_and_fetch_4:
4043 case Builtin::BI__sync_nand_and_fetch_8:
4044 case Builtin::BI__sync_nand_and_fetch_16:
4045 BuiltinIndex = 11;
4046 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00004047 break;
Mike Stump11289f42009-09-09 15:08:12 +00004048
Chris Lattnerdc046542009-05-08 06:58:22 +00004049 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004050 case Builtin::BI__sync_val_compare_and_swap_1:
4051 case Builtin::BI__sync_val_compare_and_swap_2:
4052 case Builtin::BI__sync_val_compare_and_swap_4:
4053 case Builtin::BI__sync_val_compare_and_swap_8:
4054 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004055 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00004056 NumFixed = 2;
4057 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004058
Chris Lattnerdc046542009-05-08 06:58:22 +00004059 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004060 case Builtin::BI__sync_bool_compare_and_swap_1:
4061 case Builtin::BI__sync_bool_compare_and_swap_2:
4062 case Builtin::BI__sync_bool_compare_and_swap_4:
4063 case Builtin::BI__sync_bool_compare_and_swap_8:
4064 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004065 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00004066 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00004067 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004068 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004069
JF Bastien7f0a05a2018-05-25 00:07:09 +00004070 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00004071 case Builtin::BI__sync_lock_test_and_set_1:
4072 case Builtin::BI__sync_lock_test_and_set_2:
4073 case Builtin::BI__sync_lock_test_and_set_4:
4074 case Builtin::BI__sync_lock_test_and_set_8:
4075 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004076 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00004077 break;
4078
Chris Lattnerdc046542009-05-08 06:58:22 +00004079 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00004080 case Builtin::BI__sync_lock_release_1:
4081 case Builtin::BI__sync_lock_release_2:
4082 case Builtin::BI__sync_lock_release_4:
4083 case Builtin::BI__sync_lock_release_8:
4084 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004085 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00004086 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00004087 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004088 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004089
4090 case Builtin::BI__sync_swap:
4091 case Builtin::BI__sync_swap_1:
4092 case Builtin::BI__sync_swap_2:
4093 case Builtin::BI__sync_swap_4:
4094 case Builtin::BI__sync_swap_8:
4095 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004096 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00004097 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00004098 }
Mike Stump11289f42009-09-09 15:08:12 +00004099
Chris Lattnerdc046542009-05-08 06:58:22 +00004100 // Now that we know how many fixed arguments we expect, first check that we
4101 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004102 if (TheCall->getNumArgs() < 1+NumFixed) {
4103 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4104 << 0 << 1+NumFixed << TheCall->getNumArgs()
4105 << TheCall->getCallee()->getSourceRange();
4106 return ExprError();
4107 }
Mike Stump11289f42009-09-09 15:08:12 +00004108
Hal Finkeld2208b52014-10-02 20:53:50 +00004109 if (WarnAboutSemanticsChange) {
4110 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4111 << TheCall->getCallee()->getSourceRange();
4112 }
4113
Chris Lattner5b9241b2009-05-08 15:36:58 +00004114 // Get the decl for the concrete builtin from this, we can tell what the
4115 // concrete integer type we should convert to is.
4116 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00004117 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004118 FunctionDecl *NewBuiltinDecl;
4119 if (NewBuiltinID == BuiltinID)
4120 NewBuiltinDecl = FDecl;
4121 else {
4122 // Perform builtin lookup to avoid redeclaring it.
4123 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4124 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4125 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4126 assert(Res.getFoundDecl());
4127 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004128 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004129 return ExprError();
4130 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004131
John McCallcf142162010-08-07 06:22:56 +00004132 // The first argument --- the pointer --- has a fixed type; we
4133 // deduce the types of the rest of the arguments accordingly. Walk
4134 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00004135 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004136 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00004137
Chris Lattnerdc046542009-05-08 06:58:22 +00004138 // GCC does an implicit conversion to the pointer or integer ValType. This
4139 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00004140 // Initialize the argument.
4141 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4142 ValType, /*consume*/ false);
4143 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00004144 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004145 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004146
Chris Lattnerdc046542009-05-08 06:58:22 +00004147 // Okay, we have something that *can* be converted to the right type. Check
4148 // to see if there is a potentially weird extension going on here. This can
4149 // happen when you do an atomic operation on something like an char* and
4150 // pass in 42. The 42 gets converted to char. This is even more strange
4151 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00004152 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004153 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004154 }
Mike Stump11289f42009-09-09 15:08:12 +00004155
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004156 ASTContext& Context = this->getASTContext();
4157
4158 // Create a new DeclRefExpr to refer to the new decl.
4159 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4160 Context,
4161 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004162 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004163 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004164 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004165 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004166 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004167 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004168
Chris Lattnerdc046542009-05-08 06:58:22 +00004169 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004170 // FIXME: This loses syntactic information.
4171 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4172 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4173 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004174 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004175
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004176 // Change the result type of the call to match the original value type. This
4177 // is arbitrary, but the codegen for these builtins ins design to handle it
4178 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004179 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004180
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004181 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004182}
4183
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004184/// SemaBuiltinNontemporalOverloaded - We have a call to
4185/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4186/// overloaded function based on the pointer type of its last argument.
4187///
4188/// This function goes through and does final semantic checking for these
4189/// builtins.
4190ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4191 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4192 DeclRefExpr *DRE =
4193 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4194 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4195 unsigned BuiltinID = FDecl->getBuiltinID();
4196 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4197 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4198 "Unexpected nontemporal load/store builtin!");
4199 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4200 unsigned numArgs = isStore ? 2 : 1;
4201
4202 // Ensure that we have the proper number of arguments.
4203 if (checkArgCount(*this, TheCall, numArgs))
4204 return ExprError();
4205
4206 // Inspect the last argument of the nontemporal builtin. This should always
4207 // be a pointer type, from which we imply the type of the memory access.
4208 // Because it is a pointer type, we don't have to worry about any implicit
4209 // casts here.
4210 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4211 ExprResult PointerArgResult =
4212 DefaultFunctionArrayLvalueConversion(PointerArg);
4213
4214 if (PointerArgResult.isInvalid())
4215 return ExprError();
4216 PointerArg = PointerArgResult.get();
4217 TheCall->setArg(numArgs - 1, PointerArg);
4218
4219 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4220 if (!pointerType) {
4221 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4222 << PointerArg->getType() << PointerArg->getSourceRange();
4223 return ExprError();
4224 }
4225
4226 QualType ValType = pointerType->getPointeeType();
4227
4228 // Strip any qualifiers off ValType.
4229 ValType = ValType.getUnqualifiedType();
4230 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4231 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4232 !ValType->isVectorType()) {
4233 Diag(DRE->getLocStart(),
4234 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4235 << PointerArg->getType() << PointerArg->getSourceRange();
4236 return ExprError();
4237 }
4238
4239 if (!isStore) {
4240 TheCall->setType(ValType);
4241 return TheCallResult;
4242 }
4243
4244 ExprResult ValArg = TheCall->getArg(0);
4245 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4246 Context, ValType, /*consume*/ false);
4247 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4248 if (ValArg.isInvalid())
4249 return ExprError();
4250
4251 TheCall->setArg(0, ValArg.get());
4252 TheCall->setType(Context.VoidTy);
4253 return TheCallResult;
4254}
4255
Chris Lattner6436fb62009-02-18 06:01:06 +00004256/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004257/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004258/// Note: It might also make sense to do the UTF-16 conversion here (would
4259/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004260bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004261 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004262 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4263
Douglas Gregorfb65e592011-07-27 05:40:30 +00004264 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004265 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4266 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004267 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004268 }
Mike Stump11289f42009-09-09 15:08:12 +00004269
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004270 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004271 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004272 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004273 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4274 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4275 llvm::UTF16 *ToPtr = &ToBuf[0];
4276
4277 llvm::ConversionResult Result =
4278 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4279 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004280 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004281 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004282 Diag(Arg->getLocStart(),
4283 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4284 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004285 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004286}
4287
Mehdi Amini06d367c2016-10-24 20:39:34 +00004288/// CheckObjCString - Checks that the format string argument to the os_log()
4289/// and os_trace() functions is correct, and converts it to const char *.
4290ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4291 Arg = Arg->IgnoreParenCasts();
4292 auto *Literal = dyn_cast<StringLiteral>(Arg);
4293 if (!Literal) {
4294 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4295 Literal = ObjcLiteral->getString();
4296 }
4297 }
4298
4299 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4300 return ExprError(
4301 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4302 << Arg->getSourceRange());
4303 }
4304
4305 ExprResult Result(Literal);
4306 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4307 InitializedEntity Entity =
4308 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4309 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4310 return Result;
4311}
4312
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004313/// Check that the user is calling the appropriate va_start builtin for the
4314/// target and calling convention.
4315static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4316 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4317 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004318 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004319 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004320 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4321 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004322 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004323 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4324 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4325 if (IsMSVAStart) {
4326 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004327 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004328 return S.Diag(Fn->getLocStart(),
4329 diag::err_ms_va_start_used_in_sysv_function);
4330 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004331 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004332 // On x64 Windows, don't allow this in System V ABI functions.
4333 // (Yes, that means there's no corresponding way to support variadic
4334 // System V ABI functions on Windows.)
4335 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004336 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004337 return S.Diag(Fn->getLocStart(),
4338 diag::err_va_start_used_in_wrong_abi_function)
4339 << !IsWindows;
4340 }
4341 return false;
4342 }
4343
4344 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004345 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004346 return false;
4347}
4348
4349static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4350 ParmVarDecl **LastParam = nullptr) {
4351 // Determine whether the current function, block, or obj-c method is variadic
4352 // and get its parameter list.
4353 bool IsVariadic = false;
4354 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004355 DeclContext *Caller = S.CurContext;
4356 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4357 IsVariadic = Block->isVariadic();
4358 Params = Block->parameters();
4359 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004360 IsVariadic = FD->isVariadic();
4361 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004362 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004363 IsVariadic = MD->isVariadic();
4364 // FIXME: This isn't correct for methods (results in bogus warning).
4365 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004366 } else if (isa<CapturedDecl>(Caller)) {
4367 // We don't support va_start in a CapturedDecl.
4368 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4369 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004370 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004371 // This must be some other declcontext that parses exprs.
4372 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4373 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004374 }
4375
4376 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004377 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004378 return true;
4379 }
4380
4381 if (LastParam)
4382 *LastParam = Params.empty() ? nullptr : Params.back();
4383
4384 return false;
4385}
4386
Charles Davisc7d5c942015-09-17 20:55:33 +00004387/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4388/// for validity. Emit an error and return true on failure; return false
4389/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004390bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00004391 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004392
4393 if (checkVAStartABI(*this, BuiltinID, Fn))
4394 return true;
4395
Chris Lattner08464942007-12-28 05:29:59 +00004396 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00004397 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004398 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004399 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4400 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00004401 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004402 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00004403 return true;
4404 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004405
4406 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00004407 return Diag(TheCall->getLocEnd(),
4408 diag::err_typecheck_call_too_few_args_at_least)
4409 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004410 }
4411
John McCall29ad95b2011-08-27 01:09:30 +00004412 // Type-check the first argument normally.
4413 if (checkBuiltinArgument(*this, TheCall, 0))
4414 return true;
4415
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004416 // Check that the current function is variadic, and get its last parameter.
4417 ParmVarDecl *LastParam;
4418 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004419 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004420
Chris Lattner43be2e62007-12-19 23:59:04 +00004421 // Verify that the second argument to the builtin is the last argument of the
4422 // current function or method.
4423 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004424 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004425
Nico Weber9eea7642013-05-24 23:31:57 +00004426 // These are valid if SecondArgIsLastNamedArgument is false after the next
4427 // block.
4428 QualType Type;
4429 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004430 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004431
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004432 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4433 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004434 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004435
4436 Type = PV->getType();
4437 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004438 IsCRegister =
4439 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004440 }
4441 }
Mike Stump11289f42009-09-09 15:08:12 +00004442
Chris Lattner43be2e62007-12-19 23:59:04 +00004443 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004444 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004445 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004446 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004447 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4448 // Promotable integers are UB, but enumerations need a bit of
4449 // extra checking to see what their promotable type actually is.
4450 if (!Type->isPromotableIntegerType())
4451 return false;
4452 if (!Type->isEnumeralType())
4453 return true;
4454 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4455 return !(ED &&
4456 Context.typesAreCompatible(ED->getPromotionType(), Type));
4457 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004458 unsigned Reason = 0;
4459 if (Type->isReferenceType()) Reason = 1;
4460 else if (IsCRegister) Reason = 2;
4461 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004462 Diag(ParamLoc, diag::note_parameter_type) << Type;
4463 }
4464
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004465 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004466 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004467}
Chris Lattner43be2e62007-12-19 23:59:04 +00004468
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004469bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004470 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4471 // const char *named_addr);
4472
4473 Expr *Func = Call->getCallee();
4474
4475 if (Call->getNumArgs() < 3)
4476 return Diag(Call->getLocEnd(),
4477 diag::err_typecheck_call_too_few_args_at_least)
4478 << 0 /*function call*/ << 3 << Call->getNumArgs();
4479
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004480 // Type-check the first argument normally.
4481 if (checkBuiltinArgument(*this, Call, 0))
4482 return true;
4483
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004484 // Check that the current function is variadic.
4485 if (checkVAStartIsInVariadicFunction(*this, Func))
4486 return true;
4487
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004488 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004489
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004490 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4491 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4492
4493 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4494 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4495
4496 const QualType &ConstCharPtrTy =
4497 Context.getPointerType(Context.CharTy.withConst());
4498 if (!Arg1Ty->isPointerType() ||
4499 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4500 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4501 << Arg1->getType() << ConstCharPtrTy
4502 << 1 /* different class */
4503 << 0 /* qualifier difference */
4504 << 3 /* parameter mismatch */
4505 << 2 << Arg1->getType() << ConstCharPtrTy;
4506
4507 const QualType SizeTy = Context.getSizeType();
4508 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4509 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4510 << Arg2->getType() << SizeTy
4511 << 1 /* different class */
4512 << 0 /* qualifier difference */
4513 << 3 /* parameter mismatch */
4514 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004515
4516 return false;
4517}
4518
Chris Lattner2da14fb2007-12-20 00:26:33 +00004519/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4520/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004521bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4522 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004523 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004524 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004525 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004526 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004527 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004528 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004529 << SourceRange(TheCall->getArg(2)->getLocStart(),
4530 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004531
John Wiegley01296292011-04-08 18:41:53 +00004532 ExprResult OrigArg0 = TheCall->getArg(0);
4533 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004534
Chris Lattner2da14fb2007-12-20 00:26:33 +00004535 // Do standard promotions between the two arguments, returning their common
4536 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004537 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004538 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4539 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004540
4541 // Make sure any conversions are pushed back into the call; this is
4542 // type safe since unordered compare builtins are declared as "_Bool
4543 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004544 TheCall->setArg(0, OrigArg0.get());
4545 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004546
John Wiegley01296292011-04-08 18:41:53 +00004547 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004548 return false;
4549
Chris Lattner2da14fb2007-12-20 00:26:33 +00004550 // If the common type isn't a real floating type, then the arguments were
4551 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004552 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004553 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004554 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004555 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4556 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004557
Chris Lattner2da14fb2007-12-20 00:26:33 +00004558 return false;
4559}
4560
Benjamin Kramer634fc102010-02-15 22:42:31 +00004561/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4562/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004563/// to check everything. We expect the last argument to be a floating point
4564/// value.
4565bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4566 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004567 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004568 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004569 if (TheCall->getNumArgs() > NumArgs)
4570 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004571 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004572 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004573 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004574 (*(TheCall->arg_end()-1))->getLocEnd());
4575
Benjamin Kramer64aae502010-02-16 10:07:31 +00004576 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004577
Eli Friedman7e4faac2009-08-31 20:06:00 +00004578 if (OrigArg->isTypeDependent())
4579 return false;
4580
Chris Lattner68784ef2010-05-06 05:50:07 +00004581 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004582 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004583 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004584 diag::err_typecheck_call_invalid_unary_fp)
4585 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004586
Neil Hickey88c0fac2016-12-13 16:22:50 +00004587 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004588 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004589 // Only remove standard FloatCasts, leaving other casts inplace
4590 if (Cast->getCastKind() == CK_FloatingCast) {
4591 Expr *CastArg = Cast->getSubExpr();
4592 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4593 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4594 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4595 "promotion from float to either float or double is the only expected cast here");
4596 Cast->setSubExpr(nullptr);
4597 TheCall->setArg(NumArgs-1, CastArg);
4598 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004599 }
4600 }
4601
Eli Friedman7e4faac2009-08-31 20:06:00 +00004602 return false;
4603}
4604
Tony Jiangbbc48e92017-05-24 15:13:32 +00004605// Customized Sema Checking for VSX builtins that have the following signature:
4606// vector [...] builtinName(vector [...], vector [...], const int);
4607// Which takes the same type of vectors (any legal vector type) for the first
4608// two arguments and takes compile time constant for the third argument.
4609// Example builtins are :
4610// vector double vec_xxpermdi(vector double, vector double, int);
4611// vector short vec_xxsldwi(vector short, vector short, int);
4612bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4613 unsigned ExpectedNumArgs = 3;
4614 if (TheCall->getNumArgs() < ExpectedNumArgs)
4615 return Diag(TheCall->getLocEnd(),
4616 diag::err_typecheck_call_too_few_args_at_least)
4617 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4618 << TheCall->getSourceRange();
4619
4620 if (TheCall->getNumArgs() > ExpectedNumArgs)
4621 return Diag(TheCall->getLocEnd(),
4622 diag::err_typecheck_call_too_many_args_at_most)
4623 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4624 << TheCall->getSourceRange();
4625
4626 // Check the third argument is a compile time constant
4627 llvm::APSInt Value;
4628 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4629 return Diag(TheCall->getLocStart(),
4630 diag::err_vsx_builtin_nonconstant_argument)
4631 << 3 /* argument index */ << TheCall->getDirectCallee()
4632 << SourceRange(TheCall->getArg(2)->getLocStart(),
4633 TheCall->getArg(2)->getLocEnd());
4634
4635 QualType Arg1Ty = TheCall->getArg(0)->getType();
4636 QualType Arg2Ty = TheCall->getArg(1)->getType();
4637
4638 // Check the type of argument 1 and argument 2 are vectors.
4639 SourceLocation BuiltinLoc = TheCall->getLocStart();
4640 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4641 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4642 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4643 << TheCall->getDirectCallee()
4644 << SourceRange(TheCall->getArg(0)->getLocStart(),
4645 TheCall->getArg(1)->getLocEnd());
4646 }
4647
4648 // Check the first two arguments are the same type.
4649 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4650 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4651 << TheCall->getDirectCallee()
4652 << SourceRange(TheCall->getArg(0)->getLocStart(),
4653 TheCall->getArg(1)->getLocEnd());
4654 }
4655
4656 // When default clang type checking is turned off and the customized type
4657 // checking is used, the returning type of the function must be explicitly
4658 // set. Otherwise it is _Bool by default.
4659 TheCall->setType(Arg1Ty);
4660
4661 return false;
4662}
4663
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004664/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4665// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004666ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004667 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004668 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004669 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004670 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4671 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004672
Nate Begemana0110022010-06-08 00:16:34 +00004673 // Determine which of the following types of shufflevector we're checking:
4674 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004675 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004676 QualType resType = TheCall->getArg(0)->getType();
4677 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004678
Douglas Gregorc25f7662009-05-19 22:10:17 +00004679 if (!TheCall->getArg(0)->isTypeDependent() &&
4680 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004681 QualType LHSType = TheCall->getArg(0)->getType();
4682 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004683
Craig Topperbaca3892013-07-29 06:47:04 +00004684 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4685 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004686 diag::err_vec_builtin_non_vector)
4687 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004688 << SourceRange(TheCall->getArg(0)->getLocStart(),
4689 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004690
Nate Begemana0110022010-06-08 00:16:34 +00004691 numElements = LHSType->getAs<VectorType>()->getNumElements();
4692 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004693
Nate Begemana0110022010-06-08 00:16:34 +00004694 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4695 // with mask. If so, verify that RHS is an integer vector type with the
4696 // same number of elts as lhs.
4697 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004698 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004699 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004700 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004701 diag::err_vec_builtin_incompatible_vector)
4702 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004703 << SourceRange(TheCall->getArg(1)->getLocStart(),
4704 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004705 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004706 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004707 diag::err_vec_builtin_incompatible_vector)
4708 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004709 << SourceRange(TheCall->getArg(0)->getLocStart(),
4710 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004711 } else if (numElements != numResElements) {
4712 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004713 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004714 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004715 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004716 }
4717
4718 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004719 if (TheCall->getArg(i)->isTypeDependent() ||
4720 TheCall->getArg(i)->isValueDependent())
4721 continue;
4722
Nate Begemana0110022010-06-08 00:16:34 +00004723 llvm::APSInt Result(32);
4724 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4725 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004726 diag::err_shufflevector_nonconstant_argument)
4727 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004728
Craig Topper50ad5b72013-08-03 17:40:38 +00004729 // Allow -1 which will be translated to undef in the IR.
4730 if (Result.isSigned() && Result.isAllOnesValue())
4731 continue;
4732
Chris Lattner7ab824e2008-08-10 02:05:13 +00004733 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004734 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004735 diag::err_shufflevector_argument_too_large)
4736 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004737 }
4738
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004739 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004740
Chris Lattner7ab824e2008-08-10 02:05:13 +00004741 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004742 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004743 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004744 }
4745
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004746 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4747 TheCall->getCallee()->getLocStart(),
4748 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004749}
Chris Lattner43be2e62007-12-19 23:59:04 +00004750
Hal Finkelc4d7c822013-09-18 03:29:45 +00004751/// SemaConvertVectorExpr - Handle __builtin_convertvector
4752ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4753 SourceLocation BuiltinLoc,
4754 SourceLocation RParenLoc) {
4755 ExprValueKind VK = VK_RValue;
4756 ExprObjectKind OK = OK_Ordinary;
4757 QualType DstTy = TInfo->getType();
4758 QualType SrcTy = E->getType();
4759
4760 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4761 return ExprError(Diag(BuiltinLoc,
4762 diag::err_convertvector_non_vector)
4763 << E->getSourceRange());
4764 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4765 return ExprError(Diag(BuiltinLoc,
4766 diag::err_convertvector_non_vector_type));
4767
4768 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4769 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4770 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4771 if (SrcElts != DstElts)
4772 return ExprError(Diag(BuiltinLoc,
4773 diag::err_convertvector_incompatible_vector)
4774 << E->getSourceRange());
4775 }
4776
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004777 return new (Context)
4778 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004779}
4780
Daniel Dunbarb7257262008-07-21 22:59:13 +00004781/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4782// This is declared to take (const void*, ...) and can take two
4783// optional constant int args.
4784bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004785 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004786
Chris Lattner3b054132008-11-19 05:08:23 +00004787 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004788 return Diag(TheCall->getLocEnd(),
4789 diag::err_typecheck_call_too_many_args_at_most)
4790 << 0 /*function call*/ << 3 << NumArgs
4791 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004792
4793 // Argument 0 is checked for us and the remaining arguments must be
4794 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004795 for (unsigned i = 1; i != NumArgs; ++i)
4796 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004797 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004798
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004799 return false;
4800}
4801
Hal Finkelf0417332014-07-17 14:25:55 +00004802/// SemaBuiltinAssume - Handle __assume (MS Extension).
4803// __assume does not evaluate its arguments, and should warn if its argument
4804// has side effects.
4805bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4806 Expr *Arg = TheCall->getArg(0);
4807 if (Arg->isInstantiationDependent()) return false;
4808
4809 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004810 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004811 << Arg->getSourceRange()
4812 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4813
4814 return false;
4815}
4816
David Majnemer86b1bfa2016-10-31 18:07:57 +00004817/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004818/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4819/// than 8.
4820bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4821 // The alignment must be a constant integer.
4822 Expr *Arg = TheCall->getArg(1);
4823
4824 // We can't check the value of a dependent argument.
4825 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004826 if (const auto *UE =
4827 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4828 if (UE->getKind() == UETT_AlignOf)
4829 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4830 << Arg->getSourceRange();
4831
David Majnemer51169932016-10-31 05:37:48 +00004832 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4833
4834 if (!Result.isPowerOf2())
4835 return Diag(TheCall->getLocStart(),
4836 diag::err_alignment_not_power_of_two)
4837 << Arg->getSourceRange();
4838
4839 if (Result < Context.getCharWidth())
4840 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4841 << (unsigned)Context.getCharWidth()
4842 << Arg->getSourceRange();
4843
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004844 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004845 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004846 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004847 << Arg->getSourceRange();
4848 }
4849
4850 return false;
4851}
4852
4853/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004854/// as (const void*, size_t, ...) and can take one optional constant int arg.
4855bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4856 unsigned NumArgs = TheCall->getNumArgs();
4857
4858 if (NumArgs > 3)
4859 return Diag(TheCall->getLocEnd(),
4860 diag::err_typecheck_call_too_many_args_at_most)
4861 << 0 /*function call*/ << 3 << NumArgs
4862 << TheCall->getSourceRange();
4863
4864 // The alignment must be a constant integer.
4865 Expr *Arg = TheCall->getArg(1);
4866
4867 // We can't check the value of a dependent argument.
4868 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4869 llvm::APSInt Result;
4870 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4871 return true;
4872
4873 if (!Result.isPowerOf2())
4874 return Diag(TheCall->getLocStart(),
4875 diag::err_alignment_not_power_of_two)
4876 << Arg->getSourceRange();
4877 }
4878
4879 if (NumArgs > 2) {
4880 ExprResult Arg(TheCall->getArg(2));
4881 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4882 Context.getSizeType(), false);
4883 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4884 if (Arg.isInvalid()) return true;
4885 TheCall->setArg(2, Arg.get());
4886 }
Hal Finkelf0417332014-07-17 14:25:55 +00004887
4888 return false;
4889}
4890
Mehdi Amini06d367c2016-10-24 20:39:34 +00004891bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4892 unsigned BuiltinID =
4893 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4894 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4895
4896 unsigned NumArgs = TheCall->getNumArgs();
4897 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4898 if (NumArgs < NumRequiredArgs) {
4899 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4900 << 0 /* function call */ << NumRequiredArgs << NumArgs
4901 << TheCall->getSourceRange();
4902 }
4903 if (NumArgs >= NumRequiredArgs + 0x100) {
4904 return Diag(TheCall->getLocEnd(),
4905 diag::err_typecheck_call_too_many_args_at_most)
4906 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4907 << TheCall->getSourceRange();
4908 }
4909 unsigned i = 0;
4910
4911 // For formatting call, check buffer arg.
4912 if (!IsSizeCall) {
4913 ExprResult Arg(TheCall->getArg(i));
4914 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4915 Context, Context.VoidPtrTy, false);
4916 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4917 if (Arg.isInvalid())
4918 return true;
4919 TheCall->setArg(i, Arg.get());
4920 i++;
4921 }
4922
4923 // Check string literal arg.
4924 unsigned FormatIdx = i;
4925 {
4926 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4927 if (Arg.isInvalid())
4928 return true;
4929 TheCall->setArg(i, Arg.get());
4930 i++;
4931 }
4932
4933 // Make sure variadic args are scalar.
4934 unsigned FirstDataArg = i;
4935 while (i < NumArgs) {
4936 ExprResult Arg = DefaultVariadicArgumentPromotion(
4937 TheCall->getArg(i), VariadicFunction, nullptr);
4938 if (Arg.isInvalid())
4939 return true;
4940 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4941 if (ArgSize.getQuantity() >= 0x100) {
4942 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4943 << i << (int)ArgSize.getQuantity() << 0xff
4944 << TheCall->getSourceRange();
4945 }
4946 TheCall->setArg(i, Arg.get());
4947 i++;
4948 }
4949
4950 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4951 // call to avoid duplicate diagnostics.
4952 if (!IsSizeCall) {
4953 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4954 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4955 bool Success = CheckFormatArguments(
4956 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4957 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4958 CheckedVarArgs);
4959 if (!Success)
4960 return true;
4961 }
4962
4963 if (IsSizeCall) {
4964 TheCall->setType(Context.getSizeType());
4965 } else {
4966 TheCall->setType(Context.VoidPtrTy);
4967 }
4968 return false;
4969}
4970
Eric Christopher8d0c6212010-04-17 02:26:23 +00004971/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4972/// TheCall is a constant expression.
4973bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4974 llvm::APSInt &Result) {
4975 Expr *Arg = TheCall->getArg(ArgNum);
4976 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4977 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4978
4979 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4980
4981 if (!Arg->isIntegerConstantExpr(Result, Context))
4982 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004983 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004984
Chris Lattnerd545ad12009-09-23 06:06:36 +00004985 return false;
4986}
4987
Richard Sandiford28940af2014-04-16 08:47:51 +00004988/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4989/// TheCall is a constant expression in the range [Low, High].
4990bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4991 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004992 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004993
4994 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004995 Expr *Arg = TheCall->getArg(ArgNum);
4996 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004997 return false;
4998
Eric Christopher8d0c6212010-04-17 02:26:23 +00004999 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00005000 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005001 return true;
5002
Richard Sandiford28940af2014-04-16 08:47:51 +00005003 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00005004 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00005005 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00005006
5007 return false;
5008}
5009
Simon Dardis1f90f2d2016-10-19 17:50:52 +00005010/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5011/// TheCall is a constant expression is a multiple of Num..
5012bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5013 unsigned Num) {
5014 llvm::APSInt Result;
5015
5016 // We can't check the value of a dependent argument.
5017 Expr *Arg = TheCall->getArg(ArgNum);
5018 if (Arg->isTypeDependent() || Arg->isValueDependent())
5019 return false;
5020
5021 // Check constant-ness first.
5022 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5023 return true;
5024
5025 if (Result.getSExtValue() % Num != 0)
5026 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
5027 << Num << Arg->getSourceRange();
5028
5029 return false;
5030}
5031
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005032/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5033/// TheCall is an ARM/AArch64 special register string literal.
5034bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5035 int ArgNum, unsigned ExpectedFieldNum,
5036 bool AllowName) {
5037 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5038 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5039 BuiltinID == ARM::BI__builtin_arm_rsr ||
5040 BuiltinID == ARM::BI__builtin_arm_rsrp ||
5041 BuiltinID == ARM::BI__builtin_arm_wsr ||
5042 BuiltinID == ARM::BI__builtin_arm_wsrp;
5043 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5044 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5045 BuiltinID == AArch64::BI__builtin_arm_rsr ||
5046 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5047 BuiltinID == AArch64::BI__builtin_arm_wsr ||
5048 BuiltinID == AArch64::BI__builtin_arm_wsrp;
5049 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5050
5051 // We can't check the value of a dependent argument.
5052 Expr *Arg = TheCall->getArg(ArgNum);
5053 if (Arg->isTypeDependent() || Arg->isValueDependent())
5054 return false;
5055
5056 // Check if the argument is a string literal.
5057 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5058 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
5059 << Arg->getSourceRange();
5060
5061 // Check the type of special register given.
5062 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5063 SmallVector<StringRef, 6> Fields;
5064 Reg.split(Fields, ":");
5065
5066 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5067 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5068 << Arg->getSourceRange();
5069
5070 // If the string is the name of a register then we cannot check that it is
5071 // valid here but if the string is of one the forms described in ACLE then we
5072 // can check that the supplied fields are integers and within the valid
5073 // ranges.
5074 if (Fields.size() > 1) {
5075 bool FiveFields = Fields.size() == 5;
5076
5077 bool ValidString = true;
5078 if (IsARMBuiltin) {
5079 ValidString &= Fields[0].startswith_lower("cp") ||
5080 Fields[0].startswith_lower("p");
5081 if (ValidString)
5082 Fields[0] =
5083 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5084
5085 ValidString &= Fields[2].startswith_lower("c");
5086 if (ValidString)
5087 Fields[2] = Fields[2].drop_front(1);
5088
5089 if (FiveFields) {
5090 ValidString &= Fields[3].startswith_lower("c");
5091 if (ValidString)
5092 Fields[3] = Fields[3].drop_front(1);
5093 }
5094 }
5095
5096 SmallVector<int, 5> Ranges;
5097 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00005098 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005099 else
5100 Ranges.append({15, 7, 15});
5101
5102 for (unsigned i=0; i<Fields.size(); ++i) {
5103 int IntField;
5104 ValidString &= !Fields[i].getAsInteger(10, IntField);
5105 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5106 }
5107
5108 if (!ValidString)
5109 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5110 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005111 } else if (IsAArch64Builtin && Fields.size() == 1) {
5112 // If the register name is one of those that appear in the condition below
5113 // and the special register builtin being used is one of the write builtins,
5114 // then we require that the argument provided for writing to the register
5115 // is an integer constant expression. This is because it will be lowered to
5116 // an MSR (immediate) instruction, so we need to know the immediate at
5117 // compile time.
5118 if (TheCall->getNumArgs() != 2)
5119 return false;
5120
5121 std::string RegLower = Reg.lower();
5122 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5123 RegLower != "pan" && RegLower != "uao")
5124 return false;
5125
5126 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5127 }
5128
5129 return false;
5130}
5131
Eli Friedmanc97d0142009-05-03 06:04:26 +00005132/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005133/// This checks that the target supports __builtin_longjmp and
5134/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005135bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005136 if (!Context.getTargetInfo().hasSjLjLowering())
5137 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5138 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5139
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005140 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00005141 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00005142
Eric Christopher8d0c6212010-04-17 02:26:23 +00005143 // TODO: This is less than ideal. Overload this to take a value.
5144 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5145 return true;
5146
5147 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005148 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5149 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5150
5151 return false;
5152}
5153
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005154/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5155/// This checks that the target supports __builtin_setjmp.
5156bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5157 if (!Context.getTargetInfo().hasSjLjLowering())
5158 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5159 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5160 return false;
5161}
5162
Richard Smithd7293d72013-08-05 18:49:43 +00005163namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005164
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005165class UncoveredArgHandler {
5166 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005167
5168 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005169 SmallVector<const Expr *, 4> DiagnosticExprs;
5170
5171public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005172 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005173
5174 bool hasUncoveredArg() const {
5175 return (FirstUncoveredArg >= 0);
5176 }
5177
5178 unsigned getUncoveredArg() const {
5179 assert(hasUncoveredArg() && "no uncovered argument");
5180 return FirstUncoveredArg;
5181 }
5182
5183 void setAllCovered() {
5184 // A string has been found with all arguments covered, so clear out
5185 // the diagnostics.
5186 DiagnosticExprs.clear();
5187 FirstUncoveredArg = AllCovered;
5188 }
5189
5190 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5191 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5192
5193 // Don't update if a previous string covers all arguments.
5194 if (FirstUncoveredArg == AllCovered)
5195 return;
5196
5197 // UncoveredArgHandler tracks the highest uncovered argument index
5198 // and with it all the strings that match this index.
5199 if (NewFirstUncoveredArg == FirstUncoveredArg)
5200 DiagnosticExprs.push_back(StrExpr);
5201 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5202 DiagnosticExprs.clear();
5203 DiagnosticExprs.push_back(StrExpr);
5204 FirstUncoveredArg = NewFirstUncoveredArg;
5205 }
5206 }
5207
5208 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5209};
5210
Richard Smithd7293d72013-08-05 18:49:43 +00005211enum StringLiteralCheckType {
5212 SLCT_NotALiteral,
5213 SLCT_UncheckedLiteral,
5214 SLCT_CheckedLiteral
5215};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005216
5217} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005218
Stephen Hines648c3692016-09-16 01:07:04 +00005219static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5220 BinaryOperatorKind BinOpKind,
5221 bool AddendIsRight) {
5222 unsigned BitWidth = Offset.getBitWidth();
5223 unsigned AddendBitWidth = Addend.getBitWidth();
5224 // There might be negative interim results.
5225 if (Addend.isUnsigned()) {
5226 Addend = Addend.zext(++AddendBitWidth);
5227 Addend.setIsSigned(true);
5228 }
5229 // Adjust the bit width of the APSInts.
5230 if (AddendBitWidth > BitWidth) {
5231 Offset = Offset.sext(AddendBitWidth);
5232 BitWidth = AddendBitWidth;
5233 } else if (BitWidth > AddendBitWidth) {
5234 Addend = Addend.sext(BitWidth);
5235 }
5236
5237 bool Ov = false;
5238 llvm::APSInt ResOffset = Offset;
5239 if (BinOpKind == BO_Add)
5240 ResOffset = Offset.sadd_ov(Addend, Ov);
5241 else {
5242 assert(AddendIsRight && BinOpKind == BO_Sub &&
5243 "operator must be add or sub with addend on the right");
5244 ResOffset = Offset.ssub_ov(Addend, Ov);
5245 }
5246
5247 // We add an offset to a pointer here so we should support an offset as big as
5248 // possible.
5249 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005250 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5251 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005252 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005253 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5254 return;
5255 }
5256
5257 Offset = ResOffset;
5258}
5259
5260namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005261
Stephen Hines648c3692016-09-16 01:07:04 +00005262// This is a wrapper class around StringLiteral to support offsetted string
5263// literals as format strings. It takes the offset into account when returning
5264// the string and its length or the source locations to display notes correctly.
5265class FormatStringLiteral {
5266 const StringLiteral *FExpr;
5267 int64_t Offset;
5268
5269 public:
5270 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5271 : FExpr(fexpr), Offset(Offset) {}
5272
5273 StringRef getString() const {
5274 return FExpr->getString().drop_front(Offset);
5275 }
5276
5277 unsigned getByteLength() const {
5278 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5279 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005280
Stephen Hines648c3692016-09-16 01:07:04 +00005281 unsigned getLength() const { return FExpr->getLength() - Offset; }
5282 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5283
5284 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5285
5286 QualType getType() const { return FExpr->getType(); }
5287
5288 bool isAscii() const { return FExpr->isAscii(); }
5289 bool isWide() const { return FExpr->isWide(); }
5290 bool isUTF8() const { return FExpr->isUTF8(); }
5291 bool isUTF16() const { return FExpr->isUTF16(); }
5292 bool isUTF32() const { return FExpr->isUTF32(); }
5293 bool isPascal() const { return FExpr->isPascal(); }
5294
5295 SourceLocation getLocationOfByte(
5296 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5297 const TargetInfo &Target, unsigned *StartToken = nullptr,
5298 unsigned *StartTokenByteOffset = nullptr) const {
5299 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5300 StartToken, StartTokenByteOffset);
5301 }
5302
5303 SourceLocation getLocStart() const LLVM_READONLY {
5304 return FExpr->getLocStart().getLocWithOffset(Offset);
5305 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005306
Stephen Hines648c3692016-09-16 01:07:04 +00005307 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5308};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005309
5310} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005311
5312static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005313 const Expr *OrigFormatExpr,
5314 ArrayRef<const Expr *> Args,
5315 bool HasVAListArg, unsigned format_idx,
5316 unsigned firstDataArg,
5317 Sema::FormatStringType Type,
5318 bool inFunctionCall,
5319 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005320 llvm::SmallBitVector &CheckedVarArgs,
5321 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005322
Richard Smith55ce3522012-06-25 20:30:08 +00005323// Determine if an expression is a string literal or constant string.
5324// If this function returns false on the arguments to a function expecting a
5325// format string, we will usually need to emit a warning.
5326// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005327static StringLiteralCheckType
5328checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5329 bool HasVAListArg, unsigned format_idx,
5330 unsigned firstDataArg, Sema::FormatStringType Type,
5331 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005332 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005333 UncoveredArgHandler &UncoveredArg,
5334 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005335 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005336 assert(Offset.isSigned() && "invalid offset");
5337
Douglas Gregorc25f7662009-05-19 22:10:17 +00005338 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005339 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005340
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005341 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005342
Richard Smithd7293d72013-08-05 18:49:43 +00005343 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005344 // Technically -Wformat-nonliteral does not warn about this case.
5345 // The behavior of printf and friends in this case is implementation
5346 // dependent. Ideally if the format string cannot be null then
5347 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005348 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005349
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005350 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005351 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005352 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005353 // The expression is a literal if both sub-expressions were, and it was
5354 // completely checked only if both sub-expressions were checked.
5355 const AbstractConditionalOperator *C =
5356 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005357
5358 // Determine whether it is necessary to check both sub-expressions, for
5359 // example, because the condition expression is a constant that can be
5360 // evaluated at compile time.
5361 bool CheckLeft = true, CheckRight = true;
5362
5363 bool Cond;
5364 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5365 if (Cond)
5366 CheckRight = false;
5367 else
5368 CheckLeft = false;
5369 }
5370
Stephen Hines648c3692016-09-16 01:07:04 +00005371 // We need to maintain the offsets for the right and the left hand side
5372 // separately to check if every possible indexed expression is a valid
5373 // string literal. They might have different offsets for different string
5374 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005375 StringLiteralCheckType Left;
5376 if (!CheckLeft)
5377 Left = SLCT_UncheckedLiteral;
5378 else {
5379 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5380 HasVAListArg, format_idx, firstDataArg,
5381 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005382 CheckedVarArgs, UncoveredArg, Offset);
5383 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005384 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005385 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005386 }
5387
Richard Smith55ce3522012-06-25 20:30:08 +00005388 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005389 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005390 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005391 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005392 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005393
5394 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005395 }
5396
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005397 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005398 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5399 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005400
John McCallc07a0c72011-02-17 10:25:35 +00005401 case Stmt::OpaqueValueExprClass:
5402 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5403 E = src;
5404 goto tryAgain;
5405 }
Richard Smith55ce3522012-06-25 20:30:08 +00005406 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005407
Ted Kremeneka8890832011-02-24 23:03:04 +00005408 case Stmt::PredefinedExprClass:
5409 // While __func__, etc., are technically not string literals, they
5410 // cannot contain format specifiers and thus are not a security
5411 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005412 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005413
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005414 case Stmt::DeclRefExprClass: {
5415 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005416
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005417 // As an exception, do not flag errors for variables binding to
5418 // const string literals.
5419 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5420 bool isConstant = false;
5421 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005422
Richard Smithd7293d72013-08-05 18:49:43 +00005423 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5424 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005425 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005426 isConstant = T.isConstant(S.Context) &&
5427 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005428 } else if (T->isObjCObjectPointerType()) {
5429 // In ObjC, there is usually no "const ObjectPointer" type,
5430 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005431 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005432 }
Mike Stump11289f42009-09-09 15:08:12 +00005433
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005434 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005435 if (const Expr *Init = VD->getAnyInitializer()) {
5436 // Look through initializers like const char c[] = { "foo" }
5437 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5438 if (InitList->isStringLiteralInit())
5439 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5440 }
Richard Smithd7293d72013-08-05 18:49:43 +00005441 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005442 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005443 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005444 /*InFunctionCall*/ false, CheckedVarArgs,
5445 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005446 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005447 }
Mike Stump11289f42009-09-09 15:08:12 +00005448
Anders Carlssonb012ca92009-06-28 19:55:58 +00005449 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5450 // special check to see if the format string is a function parameter
5451 // of the function calling the printf function. If the function
5452 // has an attribute indicating it is a printf-like function, then we
5453 // should suppress warnings concerning non-literals being used in a call
5454 // to a vprintf function. For example:
5455 //
5456 // void
5457 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5458 // va_list ap;
5459 // va_start(ap, fmt);
5460 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5461 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005462 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005463 if (HasVAListArg) {
5464 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5465 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5466 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005467 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005468 // adjust for implicit parameter
5469 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5470 if (MD->isInstance())
5471 ++PVIndex;
5472 // We also check if the formats are compatible.
5473 // We can't pass a 'scanf' string to a 'printf' function.
5474 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005475 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005476 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005477 }
5478 }
5479 }
5480 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005481 }
Mike Stump11289f42009-09-09 15:08:12 +00005482
Richard Smith55ce3522012-06-25 20:30:08 +00005483 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005484 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005485
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005486 case Stmt::CallExprClass:
5487 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005488 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005489 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5490 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005491 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005492 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005493 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005494 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005495 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005496 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5497 unsigned BuiltinID = FD->getBuiltinID();
5498 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5499 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5500 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005501 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005502 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005503 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005504 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005505 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005506 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005507 }
5508 }
Mike Stump11289f42009-09-09 15:08:12 +00005509
Richard Smith55ce3522012-06-25 20:30:08 +00005510 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005511 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005512 case Stmt::ObjCMessageExprClass: {
5513 const auto *ME = cast<ObjCMessageExpr>(E);
5514 if (const auto *ND = ME->getMethodDecl()) {
5515 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005516 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005517 return checkFormatStringExpr(
5518 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5519 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5520 }
5521 }
5522
5523 return SLCT_NotALiteral;
5524 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005525 case Stmt::ObjCStringLiteralClass:
5526 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005527 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005528
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005529 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005530 StrE = ObjCFExpr->getString();
5531 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005532 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005533
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005534 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005535 if (Offset.isNegative() || Offset > StrE->getLength()) {
5536 // TODO: It would be better to have an explicit warning for out of
5537 // bounds literals.
5538 return SLCT_NotALiteral;
5539 }
5540 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5541 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005542 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005543 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005544 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005545 }
Mike Stump11289f42009-09-09 15:08:12 +00005546
Richard Smith55ce3522012-06-25 20:30:08 +00005547 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005548 }
Stephen Hines648c3692016-09-16 01:07:04 +00005549 case Stmt::BinaryOperatorClass: {
5550 llvm::APSInt LResult;
5551 llvm::APSInt RResult;
5552
5553 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5554
5555 // A string literal + an int offset is still a string literal.
5556 if (BinOp->isAdditiveOp()) {
5557 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5558 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5559
5560 if (LIsInt != RIsInt) {
5561 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5562
5563 if (LIsInt) {
5564 if (BinOpKind == BO_Add) {
5565 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5566 E = BinOp->getRHS();
5567 goto tryAgain;
5568 }
5569 } else {
5570 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5571 E = BinOp->getLHS();
5572 goto tryAgain;
5573 }
5574 }
Stephen Hines648c3692016-09-16 01:07:04 +00005575 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005576
5577 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005578 }
5579 case Stmt::UnaryOperatorClass: {
5580 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5581 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005582 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005583 llvm::APSInt IndexResult;
5584 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5585 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5586 E = ASE->getBase();
5587 goto tryAgain;
5588 }
5589 }
5590
5591 return SLCT_NotALiteral;
5592 }
Mike Stump11289f42009-09-09 15:08:12 +00005593
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005594 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005595 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005596 }
5597}
5598
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005599Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005600 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005601 .Case("scanf", FST_Scanf)
5602 .Cases("printf", "printf0", FST_Printf)
5603 .Cases("NSString", "CFString", FST_NSString)
5604 .Case("strftime", FST_Strftime)
5605 .Case("strfmon", FST_Strfmon)
5606 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5607 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5608 .Case("os_trace", FST_OSLog)
5609 .Case("os_log", FST_OSLog)
5610 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005611}
5612
Jordan Rose3e0ec582012-07-19 18:10:23 +00005613/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005614/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005615/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005616bool Sema::CheckFormatArguments(const FormatAttr *Format,
5617 ArrayRef<const Expr *> Args,
5618 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005619 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005620 SourceLocation Loc, SourceRange Range,
5621 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005622 FormatStringInfo FSI;
5623 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005624 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005625 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005626 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005627 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005628}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005629
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005630bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005631 bool HasVAListArg, unsigned format_idx,
5632 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005633 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005634 SourceLocation Loc, SourceRange Range,
5635 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005636 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005637 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005638 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005639 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005640 }
Mike Stump11289f42009-09-09 15:08:12 +00005641
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005642 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005643
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005644 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005645 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005646 // Dynamically generated format strings are difficult to
5647 // automatically vet at compile time. Requiring that format strings
5648 // are string literals: (1) permits the checking of format strings by
5649 // the compiler and thereby (2) can practically remove the source of
5650 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005651
Mike Stump11289f42009-09-09 15:08:12 +00005652 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005653 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005654 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005655 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005656 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005657 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005658 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5659 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005660 /*IsFunctionCall*/ true, CheckedVarArgs,
5661 UncoveredArg,
5662 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005663
5664 // Generate a diagnostic where an uncovered argument is detected.
5665 if (UncoveredArg.hasUncoveredArg()) {
5666 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5667 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5668 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5669 }
5670
Richard Smith55ce3522012-06-25 20:30:08 +00005671 if (CT != SLCT_NotALiteral)
5672 // Literal format string found, check done!
5673 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005674
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005675 // Strftime is particular as it always uses a single 'time' argument,
5676 // so it is safe to pass a non-literal string.
5677 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005678 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005679
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005680 // Do not emit diag when the string param is a macro expansion and the
5681 // format is either NSString or CFString. This is a hack to prevent
5682 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5683 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005684 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5685 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005686 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005687
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005688 // If there are no arguments specified, warn with -Wformat-security, otherwise
5689 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005690 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005691 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5692 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005693 switch (Type) {
5694 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005695 break;
5696 case FST_Kprintf:
5697 case FST_FreeBSDKPrintf:
5698 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005699 Diag(FormatLoc, diag::note_format_security_fixit)
5700 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005701 break;
5702 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005703 Diag(FormatLoc, diag::note_format_security_fixit)
5704 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005705 break;
5706 }
5707 } else {
5708 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005709 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005710 }
Richard Smith55ce3522012-06-25 20:30:08 +00005711 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005712}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005713
Ted Kremenekab278de2010-01-28 23:39:18 +00005714namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005715
Ted Kremenek02087932010-07-16 02:11:22 +00005716class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5717protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005718 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005719 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005720 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005721 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005722 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005723 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005724 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005725 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005726 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005727 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005728 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005729 bool usesPositionalArgs = false;
5730 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005731 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005732 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005733 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005734 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005735
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005736public:
Stephen Hines648c3692016-09-16 01:07:04 +00005737 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005738 const Expr *origFormatExpr,
5739 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005740 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005741 ArrayRef<const Expr *> Args, unsigned formatIdx,
5742 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005743 llvm::SmallBitVector &CheckedVarArgs,
5744 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005745 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5746 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5747 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005748 inFunctionCall(inFunctionCall), CallType(callType),
5749 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005750 CoveredArgs.resize(numDataArgs);
5751 CoveredArgs.reset();
5752 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005753
Ted Kremenek019d2242010-01-29 01:50:07 +00005754 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005755
Ted Kremenek02087932010-07-16 02:11:22 +00005756 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005757 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005758
Jordan Rose92303592012-09-08 04:00:03 +00005759 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005760 const analyze_format_string::FormatSpecifier &FS,
5761 const analyze_format_string::ConversionSpecifier &CS,
5762 const char *startSpecifier, unsigned specifierLen,
5763 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005764
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005765 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005766 const analyze_format_string::FormatSpecifier &FS,
5767 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005768
5769 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005770 const analyze_format_string::ConversionSpecifier &CS,
5771 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005772
Craig Toppere14c0f82014-03-12 04:55:44 +00005773 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005774
Craig Toppere14c0f82014-03-12 04:55:44 +00005775 void HandleInvalidPosition(const char *startSpecifier,
5776 unsigned specifierLen,
5777 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005778
Craig Toppere14c0f82014-03-12 04:55:44 +00005779 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005780
Craig Toppere14c0f82014-03-12 04:55:44 +00005781 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005782
Richard Trieu03cf7b72011-10-28 00:41:25 +00005783 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005784 static void
5785 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5786 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5787 bool IsStringLocation, Range StringRange,
5788 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005789
Ted Kremenek02087932010-07-16 02:11:22 +00005790protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005791 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5792 const char *startSpec,
5793 unsigned specifierLen,
5794 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005795
5796 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5797 const char *startSpec,
5798 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005799
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005800 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005801 CharSourceRange getSpecifierRange(const char *startSpecifier,
5802 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005803 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005804
Ted Kremenek5739de72010-01-29 01:06:55 +00005805 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005806
5807 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5808 const analyze_format_string::ConversionSpecifier &CS,
5809 const char *startSpecifier, unsigned specifierLen,
5810 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005811
5812 template <typename Range>
5813 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5814 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005815 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005816};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005817
5818} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005819
Ted Kremenek02087932010-07-16 02:11:22 +00005820SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005821 return OrigFormatExpr->getSourceRange();
5822}
5823
Ted Kremenek02087932010-07-16 02:11:22 +00005824CharSourceRange CheckFormatHandler::
5825getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005826 SourceLocation Start = getLocationOfByte(startSpecifier);
5827 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5828
5829 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005830 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005831
5832 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005833}
5834
Ted Kremenek02087932010-07-16 02:11:22 +00005835SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005836 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5837 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005838}
5839
Ted Kremenek02087932010-07-16 02:11:22 +00005840void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5841 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5843 getLocationOfByte(startSpecifier),
5844 /*IsStringLocation*/true,
5845 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005846}
5847
Jordan Rose92303592012-09-08 04:00:03 +00005848void CheckFormatHandler::HandleInvalidLengthModifier(
5849 const analyze_format_string::FormatSpecifier &FS,
5850 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005851 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005852 using namespace analyze_format_string;
5853
5854 const LengthModifier &LM = FS.getLengthModifier();
5855 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5856
5857 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005858 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005859 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005860 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005861 getLocationOfByte(LM.getStart()),
5862 /*IsStringLocation*/true,
5863 getSpecifierRange(startSpecifier, specifierLen));
5864
5865 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5866 << FixedLM->toString()
5867 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5868
5869 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005870 FixItHint Hint;
5871 if (DiagID == diag::warn_format_nonsensical_length)
5872 Hint = FixItHint::CreateRemoval(LMRange);
5873
5874 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005875 getLocationOfByte(LM.getStart()),
5876 /*IsStringLocation*/true,
5877 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005878 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005879 }
5880}
5881
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005882void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005883 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005884 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005885 using namespace analyze_format_string;
5886
5887 const LengthModifier &LM = FS.getLengthModifier();
5888 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5889
5890 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005891 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005892 if (FixedLM) {
5893 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5894 << LM.toString() << 0,
5895 getLocationOfByte(LM.getStart()),
5896 /*IsStringLocation*/true,
5897 getSpecifierRange(startSpecifier, specifierLen));
5898
5899 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5900 << FixedLM->toString()
5901 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5902
5903 } else {
5904 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5905 << LM.toString() << 0,
5906 getLocationOfByte(LM.getStart()),
5907 /*IsStringLocation*/true,
5908 getSpecifierRange(startSpecifier, specifierLen));
5909 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005910}
5911
5912void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5913 const analyze_format_string::ConversionSpecifier &CS,
5914 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005915 using namespace analyze_format_string;
5916
5917 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005918 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005919 if (FixedCS) {
5920 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5921 << CS.toString() << /*conversion specifier*/1,
5922 getLocationOfByte(CS.getStart()),
5923 /*IsStringLocation*/true,
5924 getSpecifierRange(startSpecifier, specifierLen));
5925
5926 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5927 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5928 << FixedCS->toString()
5929 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5930 } else {
5931 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5932 << CS.toString() << /*conversion specifier*/1,
5933 getLocationOfByte(CS.getStart()),
5934 /*IsStringLocation*/true,
5935 getSpecifierRange(startSpecifier, specifierLen));
5936 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005937}
5938
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005939void CheckFormatHandler::HandlePosition(const char *startPos,
5940 unsigned posLen) {
5941 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5942 getLocationOfByte(startPos),
5943 /*IsStringLocation*/true,
5944 getSpecifierRange(startPos, posLen));
5945}
5946
Ted Kremenekd1668192010-02-27 01:41:03 +00005947void
Ted Kremenek02087932010-07-16 02:11:22 +00005948CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5949 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005950 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5951 << (unsigned) p,
5952 getLocationOfByte(startPos), /*IsStringLocation*/true,
5953 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005954}
5955
Ted Kremenek02087932010-07-16 02:11:22 +00005956void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005957 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005958 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5959 getLocationOfByte(startPos),
5960 /*IsStringLocation*/true,
5961 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005962}
5963
Ted Kremenek02087932010-07-16 02:11:22 +00005964void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005965 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005966 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005967 EmitFormatDiagnostic(
5968 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5969 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5970 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005971 }
Ted Kremenek02087932010-07-16 02:11:22 +00005972}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005973
Jordan Rose58bbe422012-07-19 18:10:08 +00005974// Note that this may return NULL if there was an error parsing or building
5975// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005976const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005977 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005978}
5979
5980void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005981 // Does the number of data arguments exceed the number of
5982 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005983 if (!HasVAListArg) {
5984 // Find any arguments that weren't covered.
5985 CoveredArgs.flip();
5986 signed notCoveredArg = CoveredArgs.find_first();
5987 if (notCoveredArg >= 0) {
5988 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005989 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5990 } else {
5991 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005992 }
5993 }
5994}
5995
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005996void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5997 const Expr *ArgExpr) {
5998 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5999 "Invalid state");
6000
6001 if (!ArgExpr)
6002 return;
6003
6004 SourceLocation Loc = ArgExpr->getLocStart();
6005
6006 if (S.getSourceManager().isInSystemMacro(Loc))
6007 return;
6008
6009 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6010 for (auto E : DiagnosticExprs)
6011 PDiag << E->getSourceRange();
6012
6013 CheckFormatHandler::EmitFormatDiagnostic(
6014 S, IsFunctionCall, DiagnosticExprs[0],
6015 PDiag, Loc, /*IsStringLocation*/false,
6016 DiagnosticExprs[0]->getSourceRange());
6017}
6018
Ted Kremenekce815422010-07-19 21:25:57 +00006019bool
6020CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6021 SourceLocation Loc,
6022 const char *startSpec,
6023 unsigned specifierLen,
6024 const char *csStart,
6025 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00006026 bool keepGoing = true;
6027 if (argIndex < NumDataArgs) {
6028 // Consider the argument coverered, even though the specifier doesn't
6029 // make sense.
6030 CoveredArgs.set(argIndex);
6031 }
6032 else {
6033 // If argIndex exceeds the number of data arguments we
6034 // don't issue a warning because that is just a cascade of warnings (and
6035 // they may have intended '%%' anyway). We don't want to continue processing
6036 // the format string after this point, however, as we will like just get
6037 // gibberish when trying to match arguments.
6038 keepGoing = false;
6039 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006040
6041 StringRef Specifier(csStart, csLen);
6042
6043 // If the specifier in non-printable, it could be the first byte of a UTF-8
6044 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6045 // hex value.
6046 std::string CodePointStr;
6047 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00006048 llvm::UTF32 CodePoint;
6049 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6050 const llvm::UTF8 *E =
6051 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6052 llvm::ConversionResult Result =
6053 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006054
Justin Lebar90910552016-09-30 00:38:45 +00006055 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006056 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00006057 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006058 }
6059
6060 llvm::raw_string_ostream OS(CodePointStr);
6061 if (CodePoint < 256)
6062 OS << "\\x" << llvm::format("%02x", CodePoint);
6063 else if (CodePoint <= 0xFFFF)
6064 OS << "\\u" << llvm::format("%04x", CodePoint);
6065 else
6066 OS << "\\U" << llvm::format("%08x", CodePoint);
6067 OS.flush();
6068 Specifier = CodePointStr;
6069 }
6070
6071 EmitFormatDiagnostic(
6072 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6073 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6074
Ted Kremenekce815422010-07-19 21:25:57 +00006075 return keepGoing;
6076}
6077
Richard Trieu03cf7b72011-10-28 00:41:25 +00006078void
6079CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6080 const char *startSpec,
6081 unsigned specifierLen) {
6082 EmitFormatDiagnostic(
6083 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6084 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6085}
6086
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006087bool
6088CheckFormatHandler::CheckNumArgs(
6089 const analyze_format_string::FormatSpecifier &FS,
6090 const analyze_format_string::ConversionSpecifier &CS,
6091 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6092
6093 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006094 PartialDiagnostic PDiag = FS.usesPositionalArg()
6095 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6096 << (argIndex+1) << NumDataArgs)
6097 : S.PDiag(diag::warn_printf_insufficient_data_args);
6098 EmitFormatDiagnostic(
6099 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6100 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006101
6102 // Since more arguments than conversion tokens are given, by extension
6103 // all arguments are covered, so mark this as so.
6104 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006105 return false;
6106 }
6107 return true;
6108}
6109
Richard Trieu03cf7b72011-10-28 00:41:25 +00006110template<typename Range>
6111void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6112 SourceLocation Loc,
6113 bool IsStringLocation,
6114 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00006115 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006116 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00006117 Loc, IsStringLocation, StringRange, FixIt);
6118}
6119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006120/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00006121/// so that the function call and string are in diagnostic messages.
6122///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006123/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00006124/// call and only one diagnostic message will be produced. Otherwise, an
6125/// extra note will be emitted pointing to location of the format string.
6126///
6127/// \param ArgumentExpr the expression that is passed as the format string
6128/// argument in the function call. Used for getting locations when two
6129/// diagnostics are emitted.
6130///
6131/// \param PDiag the callee should already have provided any strings for the
6132/// diagnostic message. This function only adds locations and fixits
6133/// to diagnostics.
6134///
6135/// \param Loc primary location for diagnostic. If two diagnostics are
6136/// required, one will be at Loc and a new SourceLocation will be created for
6137/// the other one.
6138///
6139/// \param IsStringLocation if true, Loc points to the format string should be
6140/// used for the note. Otherwise, Loc points to the argument list and will
6141/// be used with PDiag.
6142///
6143/// \param StringRange some or all of the string to highlight. This is
6144/// templated so it can accept either a CharSourceRange or a SourceRange.
6145///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006146/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00006147template <typename Range>
6148void CheckFormatHandler::EmitFormatDiagnostic(
6149 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6150 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6151 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00006152 if (InFunctionCall) {
6153 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6154 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006155 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006156 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006157 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6158 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006159
6160 const Sema::SemaDiagnosticBuilder &Note =
6161 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6162 diag::note_format_string_defined);
6163
6164 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006165 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006166 }
6167}
6168
Ted Kremenek02087932010-07-16 02:11:22 +00006169//===--- CHECK: Printf format string checking ------------------------------===//
6170
6171namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006172
Ted Kremenek02087932010-07-16 02:11:22 +00006173class CheckPrintfHandler : public CheckFormatHandler {
6174public:
Stephen Hines648c3692016-09-16 01:07:04 +00006175 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006176 const Expr *origFormatExpr,
6177 const Sema::FormatStringType type, unsigned firstDataArg,
6178 unsigned numDataArgs, bool isObjC, const char *beg,
6179 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006180 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006181 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006182 llvm::SmallBitVector &CheckedVarArgs,
6183 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006184 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6185 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6186 inFunctionCall, CallType, CheckedVarArgs,
6187 UncoveredArg) {}
6188
6189 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6190
6191 /// Returns true if '%@' specifiers are allowed in the format string.
6192 bool allowsObjCArg() const {
6193 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6194 FSType == Sema::FST_OSTrace;
6195 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006196
Ted Kremenek02087932010-07-16 02:11:22 +00006197 bool HandleInvalidPrintfConversionSpecifier(
6198 const analyze_printf::PrintfSpecifier &FS,
6199 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006200 unsigned specifierLen) override;
6201
Ted Kremenek02087932010-07-16 02:11:22 +00006202 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6203 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006204 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006205 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6206 const char *StartSpecifier,
6207 unsigned SpecifierLen,
6208 const Expr *E);
6209
Ted Kremenek02087932010-07-16 02:11:22 +00006210 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6211 const char *startSpecifier, unsigned specifierLen);
6212 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6213 const analyze_printf::OptionalAmount &Amt,
6214 unsigned type,
6215 const char *startSpecifier, unsigned specifierLen);
6216 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6217 const analyze_printf::OptionalFlag &flag,
6218 const char *startSpecifier, unsigned specifierLen);
6219 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6220 const analyze_printf::OptionalFlag &ignoredFlag,
6221 const analyze_printf::OptionalFlag &flag,
6222 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006223 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006224 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006225
6226 void HandleEmptyObjCModifierFlag(const char *startFlag,
6227 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006228
Ted Kremenek2b417712015-07-02 05:39:16 +00006229 void HandleInvalidObjCModifierFlag(const char *startFlag,
6230 unsigned flagLen) override;
6231
6232 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6233 const char *flagsEnd,
6234 const char *conversionPosition)
6235 override;
6236};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006237
6238} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006239
6240bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6241 const analyze_printf::PrintfSpecifier &FS,
6242 const char *startSpecifier,
6243 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006244 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006245 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006246
Ted Kremenekce815422010-07-19 21:25:57 +00006247 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6248 getLocationOfByte(CS.getStart()),
6249 startSpecifier, specifierLen,
6250 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006251}
6252
Ted Kremenek02087932010-07-16 02:11:22 +00006253bool CheckPrintfHandler::HandleAmount(
6254 const analyze_format_string::OptionalAmount &Amt,
6255 unsigned k, const char *startSpecifier,
6256 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006257 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006258 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006259 unsigned argIndex = Amt.getArgIndex();
6260 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006261 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6262 << k,
6263 getLocationOfByte(Amt.getStart()),
6264 /*IsStringLocation*/true,
6265 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006266 // Don't do any more checking. We will just emit
6267 // spurious errors.
6268 return false;
6269 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006270
Ted Kremenek5739de72010-01-29 01:06:55 +00006271 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006272 // Although not in conformance with C99, we also allow the argument to be
6273 // an 'unsigned int' as that is a reasonably safe case. GCC also
6274 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006275 CoveredArgs.set(argIndex);
6276 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006277 if (!Arg)
6278 return false;
6279
Ted Kremenek5739de72010-01-29 01:06:55 +00006280 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006281
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006282 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6283 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006284
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006285 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006286 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006287 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006288 << T << Arg->getSourceRange(),
6289 getLocationOfByte(Amt.getStart()),
6290 /*IsStringLocation*/true,
6291 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006292 // Don't do any more checking. We will just emit
6293 // spurious errors.
6294 return false;
6295 }
6296 }
6297 }
6298 return true;
6299}
Ted Kremenek5739de72010-01-29 01:06:55 +00006300
Tom Careb49ec692010-06-17 19:00:27 +00006301void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006302 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006303 const analyze_printf::OptionalAmount &Amt,
6304 unsigned type,
6305 const char *startSpecifier,
6306 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006307 const analyze_printf::PrintfConversionSpecifier &CS =
6308 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006309
Richard Trieu03cf7b72011-10-28 00:41:25 +00006310 FixItHint fixit =
6311 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6312 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6313 Amt.getConstantLength()))
6314 : FixItHint();
6315
6316 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6317 << type << CS.toString(),
6318 getLocationOfByte(Amt.getStart()),
6319 /*IsStringLocation*/true,
6320 getSpecifierRange(startSpecifier, specifierLen),
6321 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006322}
6323
Ted Kremenek02087932010-07-16 02:11:22 +00006324void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006325 const analyze_printf::OptionalFlag &flag,
6326 const char *startSpecifier,
6327 unsigned specifierLen) {
6328 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006329 const analyze_printf::PrintfConversionSpecifier &CS =
6330 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006331 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6332 << flag.toString() << CS.toString(),
6333 getLocationOfByte(flag.getPosition()),
6334 /*IsStringLocation*/true,
6335 getSpecifierRange(startSpecifier, specifierLen),
6336 FixItHint::CreateRemoval(
6337 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006338}
6339
6340void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006341 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006342 const analyze_printf::OptionalFlag &ignoredFlag,
6343 const analyze_printf::OptionalFlag &flag,
6344 const char *startSpecifier,
6345 unsigned specifierLen) {
6346 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006347 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6348 << ignoredFlag.toString() << flag.toString(),
6349 getLocationOfByte(ignoredFlag.getPosition()),
6350 /*IsStringLocation*/true,
6351 getSpecifierRange(startSpecifier, specifierLen),
6352 FixItHint::CreateRemoval(
6353 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006354}
6355
Ted Kremenek2b417712015-07-02 05:39:16 +00006356void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6357 unsigned flagLen) {
6358 // Warn about an empty flag.
6359 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6360 getLocationOfByte(startFlag),
6361 /*IsStringLocation*/true,
6362 getSpecifierRange(startFlag, flagLen));
6363}
6364
6365void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6366 unsigned flagLen) {
6367 // Warn about an invalid flag.
6368 auto Range = getSpecifierRange(startFlag, flagLen);
6369 StringRef flag(startFlag, flagLen);
6370 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6371 getLocationOfByte(startFlag),
6372 /*IsStringLocation*/true,
6373 Range, FixItHint::CreateRemoval(Range));
6374}
6375
6376void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6377 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6378 // Warn about using '[...]' without a '@' conversion.
6379 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6380 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6381 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6382 getLocationOfByte(conversionPosition),
6383 /*IsStringLocation*/true,
6384 Range, FixItHint::CreateRemoval(Range));
6385}
6386
Richard Smith55ce3522012-06-25 20:30:08 +00006387// Determines if the specified is a C++ class or struct containing
6388// a member with the specified name and kind (e.g. a CXXMethodDecl named
6389// "c_str()").
6390template<typename MemberKind>
6391static llvm::SmallPtrSet<MemberKind*, 1>
6392CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6393 const RecordType *RT = Ty->getAs<RecordType>();
6394 llvm::SmallPtrSet<MemberKind*, 1> Results;
6395
6396 if (!RT)
6397 return Results;
6398 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006399 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006400 return Results;
6401
Alp Tokerb6cc5922014-05-03 03:45:55 +00006402 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006403 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006404 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006405
6406 // We just need to include all members of the right kind turned up by the
6407 // filter, at this point.
6408 if (S.LookupQualifiedName(R, RT->getDecl()))
6409 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6410 NamedDecl *decl = (*I)->getUnderlyingDecl();
6411 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6412 Results.insert(FK);
6413 }
6414 return Results;
6415}
6416
Richard Smith2868a732014-02-28 01:36:39 +00006417/// Check if we could call '.c_str()' on an object.
6418///
6419/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6420/// allow the call, or if it would be ambiguous).
6421bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006422 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6423
Richard Smith2868a732014-02-28 01:36:39 +00006424 MethodSet Results =
6425 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6426 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6427 MI != ME; ++MI)
6428 if ((*MI)->getMinRequiredArguments() == 0)
6429 return true;
6430 return false;
6431}
6432
Richard Smith55ce3522012-06-25 20:30:08 +00006433// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006434// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006435// Returns true when a c_str() conversion method is found.
6436bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006437 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006438 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006439
6440 MethodSet Results =
6441 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6442
6443 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6444 MI != ME; ++MI) {
6445 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006446 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006447 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006448 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006449 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006450 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6451 << "c_str()"
6452 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6453 return true;
6454 }
6455 }
6456
6457 return false;
6458}
6459
Ted Kremenekab278de2010-01-28 23:39:18 +00006460bool
Ted Kremenek02087932010-07-16 02:11:22 +00006461CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006462 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006463 const char *startSpecifier,
6464 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006465 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006466 using namespace analyze_printf;
6467
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006468 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006469
Ted Kremenek6cd69422010-07-19 22:01:06 +00006470 if (FS.consumesDataArgument()) {
6471 if (atFirstArg) {
6472 atFirstArg = false;
6473 usesPositionalArgs = FS.usesPositionalArg();
6474 }
6475 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006476 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6477 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006478 return false;
6479 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006480 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006481
Ted Kremenekd1668192010-02-27 01:41:03 +00006482 // First check if the field width, precision, and conversion specifier
6483 // have matching data arguments.
6484 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6485 startSpecifier, specifierLen)) {
6486 return false;
6487 }
6488
6489 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6490 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006491 return false;
6492 }
6493
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006494 if (!CS.consumesDataArgument()) {
6495 // FIXME: Technically specifying a precision or field width here
6496 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006497 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006498 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006499
Ted Kremenek4a49d982010-02-26 19:18:41 +00006500 // Consume the argument.
6501 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006502 if (argIndex < NumDataArgs) {
6503 // The check to see if the argIndex is valid will come later.
6504 // We set the bit here because we may exit early from this
6505 // function if we encounter some other error.
6506 CoveredArgs.set(argIndex);
6507 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006508
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006509 // FreeBSD kernel extensions.
6510 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6511 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6512 // We need at least two arguments.
6513 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6514 return false;
6515
6516 // Claim the second argument.
6517 CoveredArgs.set(argIndex + 1);
6518
6519 // Type check the first argument (int for %b, pointer for %D)
6520 const Expr *Ex = getDataArg(argIndex);
6521 const analyze_printf::ArgType &AT =
6522 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6523 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6524 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6525 EmitFormatDiagnostic(
6526 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6527 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6528 << false << Ex->getSourceRange(),
6529 Ex->getLocStart(), /*IsStringLocation*/false,
6530 getSpecifierRange(startSpecifier, specifierLen));
6531
6532 // Type check the second argument (char * for both %b and %D)
6533 Ex = getDataArg(argIndex + 1);
6534 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6535 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6536 EmitFormatDiagnostic(
6537 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6538 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6539 << false << Ex->getSourceRange(),
6540 Ex->getLocStart(), /*IsStringLocation*/false,
6541 getSpecifierRange(startSpecifier, specifierLen));
6542
6543 return true;
6544 }
6545
Ted Kremenek4a49d982010-02-26 19:18:41 +00006546 // Check for using an Objective-C specific conversion specifier
6547 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006548 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006549 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6550 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006551 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006552
Mehdi Amini06d367c2016-10-24 20:39:34 +00006553 // %P can only be used with os_log.
6554 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6555 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6556 specifierLen);
6557 }
6558
6559 // %n is not allowed with os_log.
6560 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6561 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6562 getLocationOfByte(CS.getStart()),
6563 /*IsStringLocation*/ false,
6564 getSpecifierRange(startSpecifier, specifierLen));
6565
6566 return true;
6567 }
6568
6569 // Only scalars are allowed for os_trace.
6570 if (FSType == Sema::FST_OSTrace &&
6571 (CS.getKind() == ConversionSpecifier::PArg ||
6572 CS.getKind() == ConversionSpecifier::sArg ||
6573 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6574 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6575 specifierLen);
6576 }
6577
6578 // Check for use of public/private annotation outside of os_log().
6579 if (FSType != Sema::FST_OSLog) {
6580 if (FS.isPublic().isSet()) {
6581 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6582 << "public",
6583 getLocationOfByte(FS.isPublic().getPosition()),
6584 /*IsStringLocation*/ false,
6585 getSpecifierRange(startSpecifier, specifierLen));
6586 }
6587 if (FS.isPrivate().isSet()) {
6588 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6589 << "private",
6590 getLocationOfByte(FS.isPrivate().getPosition()),
6591 /*IsStringLocation*/ false,
6592 getSpecifierRange(startSpecifier, specifierLen));
6593 }
6594 }
6595
Tom Careb49ec692010-06-17 19:00:27 +00006596 // Check for invalid use of field width
6597 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006598 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006599 startSpecifier, specifierLen);
6600 }
6601
6602 // Check for invalid use of precision
6603 if (!FS.hasValidPrecision()) {
6604 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6605 startSpecifier, specifierLen);
6606 }
6607
Mehdi Amini06d367c2016-10-24 20:39:34 +00006608 // Precision is mandatory for %P specifier.
6609 if (CS.getKind() == ConversionSpecifier::PArg &&
6610 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6611 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6612 getLocationOfByte(startSpecifier),
6613 /*IsStringLocation*/ false,
6614 getSpecifierRange(startSpecifier, specifierLen));
6615 }
6616
Tom Careb49ec692010-06-17 19:00:27 +00006617 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006618 if (!FS.hasValidThousandsGroupingPrefix())
6619 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006620 if (!FS.hasValidLeadingZeros())
6621 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6622 if (!FS.hasValidPlusPrefix())
6623 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006624 if (!FS.hasValidSpacePrefix())
6625 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006626 if (!FS.hasValidAlternativeForm())
6627 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6628 if (!FS.hasValidLeftJustified())
6629 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6630
6631 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006632 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6633 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6634 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006635 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6636 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6637 startSpecifier, specifierLen);
6638
6639 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006640 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006641 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6642 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006643 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006644 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006645 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006646 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6647 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006648
Jordan Rose92303592012-09-08 04:00:03 +00006649 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6650 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6651
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006652 // The remaining checks depend on the data arguments.
6653 if (HasVAListArg)
6654 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006655
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006656 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006657 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006658
Jordan Rose58bbe422012-07-19 18:10:08 +00006659 const Expr *Arg = getDataArg(argIndex);
6660 if (!Arg)
6661 return true;
6662
6663 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006664}
6665
Jordan Roseaee34382012-09-05 22:56:26 +00006666static bool requiresParensToAddCast(const Expr *E) {
6667 // FIXME: We should have a general way to reason about operator
6668 // precedence and whether parens are actually needed here.
6669 // Take care of a few common cases where they aren't.
6670 const Expr *Inside = E->IgnoreImpCasts();
6671 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6672 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6673
6674 switch (Inside->getStmtClass()) {
6675 case Stmt::ArraySubscriptExprClass:
6676 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006677 case Stmt::CharacterLiteralClass:
6678 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006679 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006680 case Stmt::FloatingLiteralClass:
6681 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006682 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006683 case Stmt::ObjCArrayLiteralClass:
6684 case Stmt::ObjCBoolLiteralExprClass:
6685 case Stmt::ObjCBoxedExprClass:
6686 case Stmt::ObjCDictionaryLiteralClass:
6687 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006688 case Stmt::ObjCIvarRefExprClass:
6689 case Stmt::ObjCMessageExprClass:
6690 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006691 case Stmt::ObjCStringLiteralClass:
6692 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006693 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006694 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006695 case Stmt::UnaryOperatorClass:
6696 return false;
6697 default:
6698 return true;
6699 }
6700}
6701
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006702static std::pair<QualType, StringRef>
6703shouldNotPrintDirectly(const ASTContext &Context,
6704 QualType IntendedTy,
6705 const Expr *E) {
6706 // Use a 'while' to peel off layers of typedefs.
6707 QualType TyTy = IntendedTy;
6708 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6709 StringRef Name = UserTy->getDecl()->getName();
6710 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006711 .Case("CFIndex", Context.getNSIntegerType())
6712 .Case("NSInteger", Context.getNSIntegerType())
6713 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006714 .Case("SInt32", Context.IntTy)
6715 .Case("UInt32", Context.UnsignedIntTy)
6716 .Default(QualType());
6717
6718 if (!CastTy.isNull())
6719 return std::make_pair(CastTy, Name);
6720
6721 TyTy = UserTy->desugar();
6722 }
6723
6724 // Strip parens if necessary.
6725 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6726 return shouldNotPrintDirectly(Context,
6727 PE->getSubExpr()->getType(),
6728 PE->getSubExpr());
6729
6730 // If this is a conditional expression, then its result type is constructed
6731 // via usual arithmetic conversions and thus there might be no necessary
6732 // typedef sugar there. Recurse to operands to check for NSInteger &
6733 // Co. usage condition.
6734 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6735 QualType TrueTy, FalseTy;
6736 StringRef TrueName, FalseName;
6737
6738 std::tie(TrueTy, TrueName) =
6739 shouldNotPrintDirectly(Context,
6740 CO->getTrueExpr()->getType(),
6741 CO->getTrueExpr());
6742 std::tie(FalseTy, FalseName) =
6743 shouldNotPrintDirectly(Context,
6744 CO->getFalseExpr()->getType(),
6745 CO->getFalseExpr());
6746
6747 if (TrueTy == FalseTy)
6748 return std::make_pair(TrueTy, TrueName);
6749 else if (TrueTy.isNull())
6750 return std::make_pair(FalseTy, FalseName);
6751 else if (FalseTy.isNull())
6752 return std::make_pair(TrueTy, TrueName);
6753 }
6754
6755 return std::make_pair(QualType(), StringRef());
6756}
6757
Richard Smith55ce3522012-06-25 20:30:08 +00006758bool
6759CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6760 const char *StartSpecifier,
6761 unsigned SpecifierLen,
6762 const Expr *E) {
6763 using namespace analyze_format_string;
6764 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006765
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006766 // Now type check the data expression that matches the
6767 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006768 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006769 if (!AT.isValid())
6770 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006771
Jordan Rose598ec092012-12-05 18:44:40 +00006772 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006773 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6774 ExprTy = TET->getUnderlyingExpr()->getType();
6775 }
6776
Seth Cantrellb4802962015-03-04 03:12:10 +00006777 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6778
6779 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006780 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006781 }
Jordan Rose98709982012-06-04 22:48:57 +00006782
Jordan Rose22b74712012-09-05 22:56:19 +00006783 // Look through argument promotions for our error message's reported type.
6784 // This includes the integral and floating promotions, but excludes array
6785 // and function pointer decay; seeing that an argument intended to be a
6786 // string has type 'char [6]' is probably more confusing than 'char *'.
6787 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6788 if (ICE->getCastKind() == CK_IntegralCast ||
6789 ICE->getCastKind() == CK_FloatingCast) {
6790 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006791 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006792
6793 // Check if we didn't match because of an implicit cast from a 'char'
6794 // or 'short' to an 'int'. This is done because printf is a varargs
6795 // function.
6796 if (ICE->getType() == S.Context.IntTy ||
6797 ICE->getType() == S.Context.UnsignedIntTy) {
6798 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006799 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006800 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006801 }
Jordan Rose98709982012-06-04 22:48:57 +00006802 }
Jordan Rose598ec092012-12-05 18:44:40 +00006803 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6804 // Special case for 'a', which has type 'int' in C.
6805 // Note, however, that we do /not/ want to treat multibyte constants like
6806 // 'MooV' as characters! This form is deprecated but still exists.
6807 if (ExprTy == S.Context.IntTy)
6808 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6809 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006810 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006811
Jordan Rosebc53ed12014-05-31 04:12:14 +00006812 // Look through enums to their underlying type.
6813 bool IsEnum = false;
6814 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6815 ExprTy = EnumTy->getDecl()->getIntegerType();
6816 IsEnum = true;
6817 }
6818
Jordan Rose0e5badd2012-12-05 18:44:49 +00006819 // %C in an Objective-C context prints a unichar, not a wchar_t.
6820 // If the argument is an integer of some kind, believe the %C and suggest
6821 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006822 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006823 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006824 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6825 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6826 !ExprTy->isCharType()) {
6827 // 'unichar' is defined as a typedef of unsigned short, but we should
6828 // prefer using the typedef if it is visible.
6829 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006830
6831 // While we are here, check if the value is an IntegerLiteral that happens
6832 // to be within the valid range.
6833 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6834 const llvm::APInt &V = IL->getValue();
6835 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6836 return true;
6837 }
6838
Jordan Rose0e5badd2012-12-05 18:44:49 +00006839 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6840 Sema::LookupOrdinaryName);
6841 if (S.LookupName(Result, S.getCurScope())) {
6842 NamedDecl *ND = Result.getFoundDecl();
6843 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6844 if (TD->getUnderlyingType() == IntendedTy)
6845 IntendedTy = S.Context.getTypedefType(TD);
6846 }
6847 }
6848 }
6849
6850 // Special-case some of Darwin's platform-independence types by suggesting
6851 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006852 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006853 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006854 QualType CastTy;
6855 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6856 if (!CastTy.isNull()) {
6857 IntendedTy = CastTy;
6858 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006859 }
6860 }
6861
Jordan Rose22b74712012-09-05 22:56:19 +00006862 // We may be able to offer a FixItHint if it is a supported type.
6863 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006864 bool success =
6865 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006866
Jordan Rose22b74712012-09-05 22:56:19 +00006867 if (success) {
6868 // Get the fix string from the fixed format specifier
6869 SmallString<16> buf;
6870 llvm::raw_svector_ostream os(buf);
6871 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006872
Jordan Roseaee34382012-09-05 22:56:26 +00006873 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6874
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006875 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006876 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6877 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6878 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6879 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006880 // In this case, the specifier is wrong and should be changed to match
6881 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006882 EmitFormatDiagnostic(S.PDiag(diag)
6883 << AT.getRepresentativeTypeName(S.Context)
6884 << IntendedTy << IsEnum << E->getSourceRange(),
6885 E->getLocStart(),
6886 /*IsStringLocation*/ false, SpecRange,
6887 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006888 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006889 // The canonical type for formatting this value is different from the
6890 // actual type of the expression. (This occurs, for example, with Darwin's
6891 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6892 // should be printed as 'long' for 64-bit compatibility.)
6893 // Rather than emitting a normal format/argument mismatch, we want to
6894 // add a cast to the recommended type (and correct the format string
6895 // if necessary).
6896 SmallString<16> CastBuf;
6897 llvm::raw_svector_ostream CastFix(CastBuf);
6898 CastFix << "(";
6899 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6900 CastFix << ")";
6901
6902 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006903 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006904 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6905
6906 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6907 // If there's already a cast present, just replace it.
6908 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6909 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6910
6911 } else if (!requiresParensToAddCast(E)) {
6912 // If the expression has high enough precedence,
6913 // just write the C-style cast.
6914 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6915 CastFix.str()));
6916 } else {
6917 // Otherwise, add parens around the expression as well as the cast.
6918 CastFix << "(";
6919 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6920 CastFix.str()));
6921
Alp Tokerb6cc5922014-05-03 03:45:55 +00006922 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006923 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6924 }
6925
Jordan Rose0e5badd2012-12-05 18:44:49 +00006926 if (ShouldNotPrintDirectly) {
6927 // The expression has a type that should not be printed directly.
6928 // We extract the name from the typedef because we don't want to show
6929 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006930 StringRef Name;
6931 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6932 Name = TypedefTy->getDecl()->getName();
6933 else
6934 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006935 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006936 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006937 << E->getSourceRange(),
6938 E->getLocStart(), /*IsStringLocation=*/false,
6939 SpecRange, Hints);
6940 } else {
6941 // In this case, the expression could be printed using a different
6942 // specifier, but we've decided that the specifier is probably correct
6943 // and we should cast instead. Just use the normal warning message.
6944 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006945 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6946 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006947 << E->getSourceRange(),
6948 E->getLocStart(), /*IsStringLocation*/false,
6949 SpecRange, Hints);
6950 }
Jordan Roseaee34382012-09-05 22:56:26 +00006951 }
Jordan Rose22b74712012-09-05 22:56:19 +00006952 } else {
6953 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6954 SpecifierLen);
6955 // Since the warning for passing non-POD types to variadic functions
6956 // was deferred until now, we emit a warning for non-POD
6957 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006958 switch (S.isValidVarArgType(ExprTy)) {
6959 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006960 case Sema::VAK_ValidInCXX11: {
6961 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6962 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6963 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6964 }
Richard Smithd7293d72013-08-05 18:49:43 +00006965
Seth Cantrellb4802962015-03-04 03:12:10 +00006966 EmitFormatDiagnostic(
6967 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6968 << IsEnum << CSR << E->getSourceRange(),
6969 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6970 break;
6971 }
Richard Smithd7293d72013-08-05 18:49:43 +00006972 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006973 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006974 EmitFormatDiagnostic(
6975 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006976 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006977 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006978 << CallType
6979 << AT.getRepresentativeTypeName(S.Context)
6980 << CSR
6981 << E->getSourceRange(),
6982 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006983 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006984 break;
6985
6986 case Sema::VAK_Invalid:
6987 if (ExprTy->isObjCObjectType())
6988 EmitFormatDiagnostic(
6989 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6990 << S.getLangOpts().CPlusPlus11
6991 << ExprTy
6992 << CallType
6993 << AT.getRepresentativeTypeName(S.Context)
6994 << CSR
6995 << E->getSourceRange(),
6996 E->getLocStart(), /*IsStringLocation*/false, CSR);
6997 else
6998 // FIXME: If this is an initializer list, suggest removing the braces
6999 // or inserting a cast to the target type.
7000 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
7001 << isa<InitListExpr>(E) << ExprTy << CallType
7002 << AT.getRepresentativeTypeName(S.Context)
7003 << E->getSourceRange();
7004 break;
7005 }
7006
7007 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7008 "format string specifier index out of range");
7009 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007010 }
7011
Ted Kremenekab278de2010-01-28 23:39:18 +00007012 return true;
7013}
7014
Ted Kremenek02087932010-07-16 02:11:22 +00007015//===--- CHECK: Scanf format string checking ------------------------------===//
7016
7017namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007018
Ted Kremenek02087932010-07-16 02:11:22 +00007019class CheckScanfHandler : public CheckFormatHandler {
7020public:
Stephen Hines648c3692016-09-16 01:07:04 +00007021 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007022 const Expr *origFormatExpr, Sema::FormatStringType type,
7023 unsigned firstDataArg, unsigned numDataArgs,
7024 const char *beg, bool hasVAListArg,
7025 ArrayRef<const Expr *> Args, unsigned formatIdx,
7026 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007027 llvm::SmallBitVector &CheckedVarArgs,
7028 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007029 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7030 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7031 inFunctionCall, CallType, CheckedVarArgs,
7032 UncoveredArg) {}
7033
Ted Kremenek02087932010-07-16 02:11:22 +00007034 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7035 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007036 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00007037
7038 bool HandleInvalidScanfConversionSpecifier(
7039 const analyze_scanf::ScanfSpecifier &FS,
7040 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007041 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007042
Craig Toppere14c0f82014-03-12 04:55:44 +00007043 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00007044};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007045
7046} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007047
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007048void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7049 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007050 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7051 getLocationOfByte(end), /*IsStringLocation*/true,
7052 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007053}
7054
Ted Kremenekce815422010-07-19 21:25:57 +00007055bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7056 const analyze_scanf::ScanfSpecifier &FS,
7057 const char *startSpecifier,
7058 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007059 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007060 FS.getConversionSpecifier();
7061
7062 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7063 getLocationOfByte(CS.getStart()),
7064 startSpecifier, specifierLen,
7065 CS.getStart(), CS.getLength());
7066}
7067
Ted Kremenek02087932010-07-16 02:11:22 +00007068bool CheckScanfHandler::HandleScanfSpecifier(
7069 const analyze_scanf::ScanfSpecifier &FS,
7070 const char *startSpecifier,
7071 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00007072 using namespace analyze_scanf;
7073 using namespace analyze_format_string;
7074
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007075 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00007076
Ted Kremenek6cd69422010-07-19 22:01:06 +00007077 // Handle case where '%' and '*' don't consume an argument. These shouldn't
7078 // be used to decide if we are using positional arguments consistently.
7079 if (FS.consumesDataArgument()) {
7080 if (atFirstArg) {
7081 atFirstArg = false;
7082 usesPositionalArgs = FS.usesPositionalArg();
7083 }
7084 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007085 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7086 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007087 return false;
7088 }
Ted Kremenek02087932010-07-16 02:11:22 +00007089 }
7090
7091 // Check if the field with is non-zero.
7092 const OptionalAmount &Amt = FS.getFieldWidth();
7093 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7094 if (Amt.getConstantAmount() == 0) {
7095 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7096 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00007097 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7098 getLocationOfByte(Amt.getStart()),
7099 /*IsStringLocation*/true, R,
7100 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00007101 }
7102 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007103
Ted Kremenek02087932010-07-16 02:11:22 +00007104 if (!FS.consumesDataArgument()) {
7105 // FIXME: Technically specifying a precision or field width here
7106 // makes no sense. Worth issuing a warning at some point.
7107 return true;
7108 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007109
Ted Kremenek02087932010-07-16 02:11:22 +00007110 // Consume the argument.
7111 unsigned argIndex = FS.getArgIndex();
7112 if (argIndex < NumDataArgs) {
7113 // The check to see if the argIndex is valid will come later.
7114 // We set the bit here because we may exit early from this
7115 // function if we encounter some other error.
7116 CoveredArgs.set(argIndex);
7117 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007118
Ted Kremenek4407ea42010-07-20 20:04:47 +00007119 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007120 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007121 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7122 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007123 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007124 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007125 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007126 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7127 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007128
Jordan Rose92303592012-09-08 04:00:03 +00007129 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7130 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7131
Ted Kremenek02087932010-07-16 02:11:22 +00007132 // The remaining checks depend on the data arguments.
7133 if (HasVAListArg)
7134 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007135
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007136 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00007137 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00007138
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007139 // Check that the argument type matches the format specifier.
7140 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007141 if (!Ex)
7142 return true;
7143
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00007144 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00007145
7146 if (!AT.isValid()) {
7147 return true;
7148 }
7149
Seth Cantrellb4802962015-03-04 03:12:10 +00007150 analyze_format_string::ArgType::MatchKind match =
7151 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00007152 if (match == analyze_format_string::ArgType::Match) {
7153 return true;
7154 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007155
Seth Cantrell79340072015-03-04 05:58:08 +00007156 ScanfSpecifier fixedFS = FS;
7157 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7158 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007159
Seth Cantrell79340072015-03-04 05:58:08 +00007160 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7161 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7162 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7163 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007164
Seth Cantrell79340072015-03-04 05:58:08 +00007165 if (success) {
7166 // Get the fix string from the fixed format specifier.
7167 SmallString<128> buf;
7168 llvm::raw_svector_ostream os(buf);
7169 fixedFS.toString(os);
7170
7171 EmitFormatDiagnostic(
7172 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7173 << Ex->getType() << false << Ex->getSourceRange(),
7174 Ex->getLocStart(),
7175 /*IsStringLocation*/ false,
7176 getSpecifierRange(startSpecifier, specifierLen),
7177 FixItHint::CreateReplacement(
7178 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7179 } else {
7180 EmitFormatDiagnostic(S.PDiag(diag)
7181 << AT.getRepresentativeTypeName(S.Context)
7182 << Ex->getType() << false << Ex->getSourceRange(),
7183 Ex->getLocStart(),
7184 /*IsStringLocation*/ false,
7185 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007186 }
7187
Ted Kremenek02087932010-07-16 02:11:22 +00007188 return true;
7189}
7190
Stephen Hines648c3692016-09-16 01:07:04 +00007191static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007192 const Expr *OrigFormatExpr,
7193 ArrayRef<const Expr *> Args,
7194 bool HasVAListArg, unsigned format_idx,
7195 unsigned firstDataArg,
7196 Sema::FormatStringType Type,
7197 bool inFunctionCall,
7198 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007199 llvm::SmallBitVector &CheckedVarArgs,
7200 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007201 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007202 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007203 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007204 S, inFunctionCall, Args[format_idx],
7205 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007206 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007207 return;
7208 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007209
Ted Kremenekab278de2010-01-28 23:39:18 +00007210 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007211 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007212 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007213 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007214 const ConstantArrayType *T =
7215 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007216 assert(T && "String literal not of constant array type!");
7217 size_t TypeSize = T->getSize().getZExtValue();
7218 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007219 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007220
7221 // Emit a warning if the string literal is truncated and does not contain an
7222 // embedded null character.
7223 if (TypeSize <= StrRef.size() &&
7224 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7225 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007226 S, inFunctionCall, Args[format_idx],
7227 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007228 FExpr->getLocStart(),
7229 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7230 return;
7231 }
7232
Ted Kremenekab278de2010-01-28 23:39:18 +00007233 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007234 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007235 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007236 S, inFunctionCall, Args[format_idx],
7237 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007238 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007239 return;
7240 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007241
7242 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007243 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7244 Type == Sema::FST_OSTrace) {
7245 CheckPrintfHandler H(
7246 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7247 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7248 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7249 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007250
Hans Wennborg23926bd2011-12-15 10:25:47 +00007251 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007252 S.getLangOpts(),
7253 S.Context.getTargetInfo(),
7254 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007255 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007256 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007257 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7258 numDataArgs, Str, HasVAListArg, Args, format_idx,
7259 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007260
Hans Wennborg23926bd2011-12-15 10:25:47 +00007261 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007262 S.getLangOpts(),
7263 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007264 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007265 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007266}
7267
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007268bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7269 // Str - The format string. NOTE: this is NOT null-terminated!
7270 StringRef StrRef = FExpr->getString();
7271 const char *Str = StrRef.data();
7272 // Account for cases where the string literal is truncated in a declaration.
7273 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7274 assert(T && "String literal not of constant array type!");
7275 size_t TypeSize = T->getSize().getZExtValue();
7276 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7277 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7278 getLangOpts(),
7279 Context.getTargetInfo());
7280}
7281
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007282//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7283
7284// Returns the related absolute value function that is larger, of 0 if one
7285// does not exist.
7286static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7287 switch (AbsFunction) {
7288 default:
7289 return 0;
7290
7291 case Builtin::BI__builtin_abs:
7292 return Builtin::BI__builtin_labs;
7293 case Builtin::BI__builtin_labs:
7294 return Builtin::BI__builtin_llabs;
7295 case Builtin::BI__builtin_llabs:
7296 return 0;
7297
7298 case Builtin::BI__builtin_fabsf:
7299 return Builtin::BI__builtin_fabs;
7300 case Builtin::BI__builtin_fabs:
7301 return Builtin::BI__builtin_fabsl;
7302 case Builtin::BI__builtin_fabsl:
7303 return 0;
7304
7305 case Builtin::BI__builtin_cabsf:
7306 return Builtin::BI__builtin_cabs;
7307 case Builtin::BI__builtin_cabs:
7308 return Builtin::BI__builtin_cabsl;
7309 case Builtin::BI__builtin_cabsl:
7310 return 0;
7311
7312 case Builtin::BIabs:
7313 return Builtin::BIlabs;
7314 case Builtin::BIlabs:
7315 return Builtin::BIllabs;
7316 case Builtin::BIllabs:
7317 return 0;
7318
7319 case Builtin::BIfabsf:
7320 return Builtin::BIfabs;
7321 case Builtin::BIfabs:
7322 return Builtin::BIfabsl;
7323 case Builtin::BIfabsl:
7324 return 0;
7325
7326 case Builtin::BIcabsf:
7327 return Builtin::BIcabs;
7328 case Builtin::BIcabs:
7329 return Builtin::BIcabsl;
7330 case Builtin::BIcabsl:
7331 return 0;
7332 }
7333}
7334
7335// Returns the argument type of the absolute value function.
7336static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7337 unsigned AbsType) {
7338 if (AbsType == 0)
7339 return QualType();
7340
7341 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7342 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7343 if (Error != ASTContext::GE_None)
7344 return QualType();
7345
7346 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7347 if (!FT)
7348 return QualType();
7349
7350 if (FT->getNumParams() != 1)
7351 return QualType();
7352
7353 return FT->getParamType(0);
7354}
7355
7356// Returns the best absolute value function, or zero, based on type and
7357// current absolute value function.
7358static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7359 unsigned AbsFunctionKind) {
7360 unsigned BestKind = 0;
7361 uint64_t ArgSize = Context.getTypeSize(ArgType);
7362 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7363 Kind = getLargerAbsoluteValueFunction(Kind)) {
7364 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7365 if (Context.getTypeSize(ParamType) >= ArgSize) {
7366 if (BestKind == 0)
7367 BestKind = Kind;
7368 else if (Context.hasSameType(ParamType, ArgType)) {
7369 BestKind = Kind;
7370 break;
7371 }
7372 }
7373 }
7374 return BestKind;
7375}
7376
7377enum AbsoluteValueKind {
7378 AVK_Integer,
7379 AVK_Floating,
7380 AVK_Complex
7381};
7382
7383static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7384 if (T->isIntegralOrEnumerationType())
7385 return AVK_Integer;
7386 if (T->isRealFloatingType())
7387 return AVK_Floating;
7388 if (T->isAnyComplexType())
7389 return AVK_Complex;
7390
7391 llvm_unreachable("Type not integer, floating, or complex");
7392}
7393
7394// Changes the absolute value function to a different type. Preserves whether
7395// the function is a builtin.
7396static unsigned changeAbsFunction(unsigned AbsKind,
7397 AbsoluteValueKind ValueKind) {
7398 switch (ValueKind) {
7399 case AVK_Integer:
7400 switch (AbsKind) {
7401 default:
7402 return 0;
7403 case Builtin::BI__builtin_fabsf:
7404 case Builtin::BI__builtin_fabs:
7405 case Builtin::BI__builtin_fabsl:
7406 case Builtin::BI__builtin_cabsf:
7407 case Builtin::BI__builtin_cabs:
7408 case Builtin::BI__builtin_cabsl:
7409 return Builtin::BI__builtin_abs;
7410 case Builtin::BIfabsf:
7411 case Builtin::BIfabs:
7412 case Builtin::BIfabsl:
7413 case Builtin::BIcabsf:
7414 case Builtin::BIcabs:
7415 case Builtin::BIcabsl:
7416 return Builtin::BIabs;
7417 }
7418 case AVK_Floating:
7419 switch (AbsKind) {
7420 default:
7421 return 0;
7422 case Builtin::BI__builtin_abs:
7423 case Builtin::BI__builtin_labs:
7424 case Builtin::BI__builtin_llabs:
7425 case Builtin::BI__builtin_cabsf:
7426 case Builtin::BI__builtin_cabs:
7427 case Builtin::BI__builtin_cabsl:
7428 return Builtin::BI__builtin_fabsf;
7429 case Builtin::BIabs:
7430 case Builtin::BIlabs:
7431 case Builtin::BIllabs:
7432 case Builtin::BIcabsf:
7433 case Builtin::BIcabs:
7434 case Builtin::BIcabsl:
7435 return Builtin::BIfabsf;
7436 }
7437 case AVK_Complex:
7438 switch (AbsKind) {
7439 default:
7440 return 0;
7441 case Builtin::BI__builtin_abs:
7442 case Builtin::BI__builtin_labs:
7443 case Builtin::BI__builtin_llabs:
7444 case Builtin::BI__builtin_fabsf:
7445 case Builtin::BI__builtin_fabs:
7446 case Builtin::BI__builtin_fabsl:
7447 return Builtin::BI__builtin_cabsf;
7448 case Builtin::BIabs:
7449 case Builtin::BIlabs:
7450 case Builtin::BIllabs:
7451 case Builtin::BIfabsf:
7452 case Builtin::BIfabs:
7453 case Builtin::BIfabsl:
7454 return Builtin::BIcabsf;
7455 }
7456 }
7457 llvm_unreachable("Unable to convert function");
7458}
7459
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007460static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007461 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7462 if (!FnInfo)
7463 return 0;
7464
7465 switch (FDecl->getBuiltinID()) {
7466 default:
7467 return 0;
7468 case Builtin::BI__builtin_abs:
7469 case Builtin::BI__builtin_fabs:
7470 case Builtin::BI__builtin_fabsf:
7471 case Builtin::BI__builtin_fabsl:
7472 case Builtin::BI__builtin_labs:
7473 case Builtin::BI__builtin_llabs:
7474 case Builtin::BI__builtin_cabs:
7475 case Builtin::BI__builtin_cabsf:
7476 case Builtin::BI__builtin_cabsl:
7477 case Builtin::BIabs:
7478 case Builtin::BIlabs:
7479 case Builtin::BIllabs:
7480 case Builtin::BIfabs:
7481 case Builtin::BIfabsf:
7482 case Builtin::BIfabsl:
7483 case Builtin::BIcabs:
7484 case Builtin::BIcabsf:
7485 case Builtin::BIcabsl:
7486 return FDecl->getBuiltinID();
7487 }
7488 llvm_unreachable("Unknown Builtin type");
7489}
7490
7491// If the replacement is valid, emit a note with replacement function.
7492// Additionally, suggest including the proper header if not already included.
7493static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007494 unsigned AbsKind, QualType ArgType) {
7495 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007496 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007497 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007498 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7499 FunctionName = "std::abs";
7500 if (ArgType->isIntegralOrEnumerationType()) {
7501 HeaderName = "cstdlib";
7502 } else if (ArgType->isRealFloatingType()) {
7503 HeaderName = "cmath";
7504 } else {
7505 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007506 }
Richard Trieubeffb832014-04-15 23:47:53 +00007507
7508 // Lookup all std::abs
7509 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007510 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007511 R.suppressDiagnostics();
7512 S.LookupQualifiedName(R, Std);
7513
7514 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007515 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007516 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7517 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7518 } else {
7519 FDecl = dyn_cast<FunctionDecl>(I);
7520 }
7521 if (!FDecl)
7522 continue;
7523
7524 // Found std::abs(), check that they are the right ones.
7525 if (FDecl->getNumParams() != 1)
7526 continue;
7527
7528 // Check that the parameter type can handle the argument.
7529 QualType ParamType = FDecl->getParamDecl(0)->getType();
7530 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7531 S.Context.getTypeSize(ArgType) <=
7532 S.Context.getTypeSize(ParamType)) {
7533 // Found a function, don't need the header hint.
7534 EmitHeaderHint = false;
7535 break;
7536 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007537 }
Richard Trieubeffb832014-04-15 23:47:53 +00007538 }
7539 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007540 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007541 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7542
7543 if (HeaderName) {
7544 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7545 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7546 R.suppressDiagnostics();
7547 S.LookupName(R, S.getCurScope());
7548
7549 if (R.isSingleResult()) {
7550 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7551 if (FD && FD->getBuiltinID() == AbsKind) {
7552 EmitHeaderHint = false;
7553 } else {
7554 return;
7555 }
7556 } else if (!R.empty()) {
7557 return;
7558 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007559 }
7560 }
7561
7562 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007563 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007564
Richard Trieubeffb832014-04-15 23:47:53 +00007565 if (!HeaderName)
7566 return;
7567
7568 if (!EmitHeaderHint)
7569 return;
7570
Alp Toker5d96e0a2014-07-11 20:53:51 +00007571 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7572 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007573}
7574
Richard Trieua7f30b12016-12-06 01:42:28 +00007575template <std::size_t StrLen>
7576static bool IsStdFunction(const FunctionDecl *FDecl,
7577 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007578 if (!FDecl)
7579 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007580 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007581 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007582 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007583 return false;
7584
7585 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007586}
7587
7588// Warn when using the wrong abs() function.
7589void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007590 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007591 if (Call->getNumArgs() != 1)
7592 return;
7593
7594 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007595 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007596 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007597 return;
7598
7599 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7600 QualType ParamType = Call->getArg(0)->getType();
7601
Alp Toker5d96e0a2014-07-11 20:53:51 +00007602 // Unsigned types cannot be negative. Suggest removing the absolute value
7603 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007604 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007605 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007606 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007607 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7608 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007609 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007610 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7611 return;
7612 }
7613
David Majnemer7f77eb92015-11-15 03:04:34 +00007614 // Taking the absolute value of a pointer is very suspicious, they probably
7615 // wanted to index into an array, dereference a pointer, call a function, etc.
7616 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7617 unsigned DiagType = 0;
7618 if (ArgType->isFunctionType())
7619 DiagType = 1;
7620 else if (ArgType->isArrayType())
7621 DiagType = 2;
7622
7623 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7624 return;
7625 }
7626
Richard Trieubeffb832014-04-15 23:47:53 +00007627 // std::abs has overloads which prevent most of the absolute value problems
7628 // from occurring.
7629 if (IsStdAbs)
7630 return;
7631
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007632 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7633 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7634
7635 // The argument and parameter are the same kind. Check if they are the right
7636 // size.
7637 if (ArgValueKind == ParamValueKind) {
7638 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7639 return;
7640
7641 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7642 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7643 << FDecl << ArgType << ParamType;
7644
7645 if (NewAbsKind == 0)
7646 return;
7647
7648 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007649 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007650 return;
7651 }
7652
7653 // ArgValueKind != ParamValueKind
7654 // The wrong type of absolute value function was used. Attempt to find the
7655 // proper one.
7656 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7657 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7658 if (NewAbsKind == 0)
7659 return;
7660
7661 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7662 << FDecl << ParamValueKind << ArgValueKind;
7663
7664 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007665 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007666}
7667
Richard Trieu67c00712016-12-05 23:41:46 +00007668//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007669void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7670 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007671 if (!Call || !FDecl) return;
7672
7673 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007674 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007675 if (Call->getExprLoc().isMacroID()) return;
7676
7677 // Only care about the one template argument, two function parameter std::max
7678 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007679 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007680 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7681 if (!ArgList) return;
7682 if (ArgList->size() != 1) return;
7683
7684 // Check that template type argument is unsigned integer.
7685 const auto& TA = ArgList->get(0);
7686 if (TA.getKind() != TemplateArgument::Type) return;
7687 QualType ArgType = TA.getAsType();
7688 if (!ArgType->isUnsignedIntegerType()) return;
7689
7690 // See if either argument is a literal zero.
7691 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7692 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7693 if (!MTE) return false;
7694 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7695 if (!Num) return false;
7696 if (Num->getValue() != 0) return false;
7697 return true;
7698 };
7699
7700 const Expr *FirstArg = Call->getArg(0);
7701 const Expr *SecondArg = Call->getArg(1);
7702 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7703 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7704
7705 // Only warn when exactly one argument is zero.
7706 if (IsFirstArgZero == IsSecondArgZero) return;
7707
7708 SourceRange FirstRange = FirstArg->getSourceRange();
7709 SourceRange SecondRange = SecondArg->getSourceRange();
7710
7711 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7712
7713 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7714 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7715
7716 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7717 SourceRange RemovalRange;
7718 if (IsFirstArgZero) {
7719 RemovalRange = SourceRange(FirstRange.getBegin(),
7720 SecondRange.getBegin().getLocWithOffset(-1));
7721 } else {
7722 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7723 SecondRange.getEnd());
7724 }
7725
7726 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7727 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7728 << FixItHint::CreateRemoval(RemovalRange);
7729}
7730
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007731//===--- CHECK: Standard memory functions ---------------------------------===//
7732
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007733/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007734/// such as memcmp, strncat, etc and warns if it's a comparison.
7735///
7736/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7737static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7738 IdentifierInfo *FnName,
7739 SourceLocation FnLoc,
7740 SourceLocation RParenLoc) {
7741 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7742 if (!Size)
7743 return false;
7744
Richard Smithc70f1d62017-12-14 15:16:18 +00007745 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7746 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007747 return false;
7748
Nico Weber0e6daef2013-12-26 23:38:39 +00007749 SourceRange SizeRange = Size->getSourceRange();
7750 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7751 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007752 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007753 << FnName << FixItHint::CreateInsertion(
7754 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007755 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007756 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007757 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007758 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7759 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007760
7761 return true;
7762}
7763
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007764/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007765/// (e.g., whether it has a vtable).
7766static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7767 bool &IsContained) {
7768 // Look through array types while ignoring qualifiers.
7769 const Type *Ty = T->getBaseElementTypeUnsafe();
7770 IsContained = false;
7771
7772 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7773 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007774 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007775 return nullptr;
7776
7777 if (RD->isDynamicClass())
7778 return RD;
7779
7780 // Check all the fields. If any bases were dynamic, the class is dynamic.
7781 // It's impossible for a class to transitively contain itself by value, so
7782 // infinite recursion is impossible.
7783 for (auto *FD : RD->fields()) {
7784 bool SubContained;
7785 if (const CXXRecordDecl *ContainedRD =
7786 getContainedDynamicClass(FD->getType(), SubContained)) {
7787 IsContained = true;
7788 return ContainedRD;
7789 }
7790 }
7791
7792 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007793}
7794
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007795/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007796/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007797static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007798 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007799 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007800 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007801 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007802
Craig Topperc3ec1492014-05-26 06:22:03 +00007803 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007804}
7805
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007806/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007807static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007808 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7809 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007810 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007811 return SizeOf->getTypeOfArgument();
7812
7813 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007814}
7815
Akira Hatanaka2be04412018-04-17 19:13:41 +00007816namespace {
7817
7818struct SearchNonTrivialToInitializeField
7819 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7820 using Super =
7821 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7822
7823 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7824
7825 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7826 SourceLocation SL) {
7827 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7828 asDerived().visitArray(PDIK, AT, SL);
7829 return;
7830 }
7831
7832 Super::visitWithKind(PDIK, FT, SL);
7833 }
7834
7835 void visitARCStrong(QualType FT, SourceLocation SL) {
7836 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7837 }
7838 void visitARCWeak(QualType FT, SourceLocation SL) {
7839 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7840 }
7841 void visitStruct(QualType FT, SourceLocation SL) {
7842 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7843 visit(FD->getType(), FD->getLocation());
7844 }
7845 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7846 const ArrayType *AT, SourceLocation SL) {
7847 visit(getContext().getBaseElementType(AT), SL);
7848 }
7849 void visitTrivial(QualType FT, SourceLocation SL) {}
7850
7851 static void diag(QualType RT, const Expr *E, Sema &S) {
7852 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7853 }
7854
7855 ASTContext &getContext() { return S.getASTContext(); }
7856
7857 const Expr *E;
7858 Sema &S;
7859};
7860
7861struct SearchNonTrivialToCopyField
7862 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7863 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7864
7865 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7866
7867 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7868 SourceLocation SL) {
7869 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7870 asDerived().visitArray(PCK, AT, SL);
7871 return;
7872 }
7873
7874 Super::visitWithKind(PCK, FT, SL);
7875 }
7876
7877 void visitARCStrong(QualType FT, SourceLocation SL) {
7878 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7879 }
7880 void visitARCWeak(QualType FT, SourceLocation SL) {
7881 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7882 }
7883 void visitStruct(QualType FT, SourceLocation SL) {
7884 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7885 visit(FD->getType(), FD->getLocation());
7886 }
7887 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7888 SourceLocation SL) {
7889 visit(getContext().getBaseElementType(AT), SL);
7890 }
7891 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7892 SourceLocation SL) {}
7893 void visitTrivial(QualType FT, SourceLocation SL) {}
7894 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7895
7896 static void diag(QualType RT, const Expr *E, Sema &S) {
7897 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7898 }
7899
7900 ASTContext &getContext() { return S.getASTContext(); }
7901
7902 const Expr *E;
7903 Sema &S;
7904};
7905
7906}
7907
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007908/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007909///
Chandler Carruthac687262011-06-03 06:23:57 +00007910/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007911/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7912/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007913///
7914/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007915void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007916 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007917 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007918 assert(BId != 0);
7919
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007920 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007921 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007922 unsigned ExpectedNumArgs =
7923 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007924 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007925 return;
7926
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007927 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007928 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007929 unsigned LenArg =
7930 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007931 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007932
Nico Weber0e6daef2013-12-26 23:38:39 +00007933 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7934 Call->getLocStart(), Call->getRParenLoc()))
7935 return;
7936
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007937 // We have special checking when the length is a sizeof expression.
7938 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7939 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7940 llvm::FoldingSetNodeID SizeOfArgID;
7941
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007942 // Although widely used, 'bzero' is not a standard function. Be more strict
7943 // with the argument types before allowing diagnostics and only allow the
7944 // form bzero(ptr, sizeof(...)).
7945 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7946 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7947 return;
7948
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007949 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7950 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007951 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007952
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007953 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007954 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007955 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007956 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007957
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007958 // Never warn about void type pointers. This can be used to suppress
7959 // false positives.
7960 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007961 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007962
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007963 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7964 // actually comparing the expressions for equality. Because computing the
7965 // expression IDs can be expensive, we only do this if the diagnostic is
7966 // enabled.
7967 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007968 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7969 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007970 // We only compute IDs for expressions if the warning is enabled, and
7971 // cache the sizeof arg's ID.
7972 if (SizeOfArgID == llvm::FoldingSetNodeID())
7973 SizeOfArg->Profile(SizeOfArgID, Context, true);
7974 llvm::FoldingSetNodeID DestID;
7975 Dest->Profile(DestID, Context, true);
7976 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007977 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7978 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007979 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007980 StringRef ReadableName = FnName->getName();
7981
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007982 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007983 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007984 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007985 if (!PointeeTy->isIncompleteType() &&
7986 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007987 ActionIdx = 2; // If the pointee's size is sizeof(char),
7988 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007989
7990 // If the function is defined as a builtin macro, do not show macro
7991 // expansion.
7992 SourceLocation SL = SizeOfArg->getExprLoc();
7993 SourceRange DSR = Dest->getSourceRange();
7994 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007995 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007996
7997 if (SM.isMacroArgExpansion(SL)) {
7998 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7999 SL = SM.getSpellingLoc(SL);
8000 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8001 SM.getSpellingLoc(DSR.getEnd()));
8002 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8003 SM.getSpellingLoc(SSR.getEnd()));
8004 }
8005
Anna Zaksd08d9152012-05-30 23:14:52 +00008006 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008007 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00008008 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00008009 << PointeeTy
8010 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00008011 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00008012 << SSR);
8013 DiagRuntimeBehavior(SL, SizeOfArg,
8014 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8015 << ActionIdx
8016 << SSR);
8017
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008018 break;
8019 }
8020 }
8021
8022 // Also check for cases where the sizeof argument is the exact same
8023 // type as the memory argument, and where it points to a user-defined
8024 // record type.
8025 if (SizeOfArgTy != QualType()) {
8026 if (PointeeTy->isRecordType() &&
8027 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8028 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8029 PDiag(diag::warn_sizeof_pointer_type_memaccess)
8030 << FnName << SizeOfArgTy << ArgIdx
8031 << PointeeTy << Dest->getSourceRange()
8032 << LenExpr->getSourceRange());
8033 break;
8034 }
Nico Weberc5e73862011-06-14 16:14:58 +00008035 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00008036 } else if (DestTy->isArrayType()) {
8037 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00008038 }
Nico Weberc5e73862011-06-14 16:14:58 +00008039
Nico Weberc44b35e2015-03-21 17:37:46 +00008040 if (PointeeTy == QualType())
8041 continue;
Anna Zaks22122702012-01-17 00:37:07 +00008042
Nico Weberc44b35e2015-03-21 17:37:46 +00008043 // Always complain about dynamic classes.
8044 bool IsContained;
8045 if (const CXXRecordDecl *ContainedRD =
8046 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00008047
Nico Weberc44b35e2015-03-21 17:37:46 +00008048 unsigned OperationType = 0;
8049 // "overwritten" if we're warning about the destination for any call
8050 // but memcmp; otherwise a verb appropriate to the call.
8051 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
8052 if (BId == Builtin::BImemcpy)
8053 OperationType = 1;
8054 else if(BId == Builtin::BImemmove)
8055 OperationType = 2;
8056 else if (BId == Builtin::BImemcmp)
8057 OperationType = 3;
8058 }
8059
John McCall31168b02011-06-15 23:02:42 +00008060 DiagRuntimeBehavior(
8061 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00008062 PDiag(diag::warn_dyn_class_memaccess)
8063 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
8064 << FnName << IsContained << ContainedRD << OperationType
8065 << Call->getCallee()->getSourceRange());
8066 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8067 BId != Builtin::BImemset)
8068 DiagRuntimeBehavior(
8069 Dest->getExprLoc(), Dest,
8070 PDiag(diag::warn_arc_object_memaccess)
8071 << ArgIdx << FnName << PointeeTy
8072 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00008073 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8074 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8075 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8076 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8077 PDiag(diag::warn_cstruct_memaccess)
8078 << ArgIdx << FnName << PointeeTy << 0);
8079 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8080 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8081 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8082 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8083 PDiag(diag::warn_cstruct_memaccess)
8084 << ArgIdx << FnName << PointeeTy << 1);
8085 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8086 } else {
8087 continue;
8088 }
8089 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00008090 continue;
8091
8092 DiagRuntimeBehavior(
8093 Dest->getExprLoc(), Dest,
8094 PDiag(diag::note_bad_memaccess_silence)
8095 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8096 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008097 }
8098}
8099
Ted Kremenek6865f772011-08-18 20:55:45 +00008100// A little helper routine: ignore addition and subtraction of integer literals.
8101// This intentionally does not ignore all integer constant expressions because
8102// we don't want to remove sizeof().
8103static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8104 Ex = Ex->IgnoreParenCasts();
8105
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008106 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00008107 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8108 if (!BO || !BO->isAdditiveOp())
8109 break;
8110
8111 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8112 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8113
8114 if (isa<IntegerLiteral>(RHS))
8115 Ex = LHS;
8116 else if (isa<IntegerLiteral>(LHS))
8117 Ex = RHS;
8118 else
8119 break;
8120 }
8121
8122 return Ex;
8123}
8124
Anna Zaks13b08572012-08-08 21:42:23 +00008125static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8126 ASTContext &Context) {
8127 // Only handle constant-sized or VLAs, but not flexible members.
8128 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8129 // Only issue the FIXIT for arrays of size > 1.
8130 if (CAT->getSize().getSExtValue() <= 1)
8131 return false;
8132 } else if (!Ty->isVariableArrayType()) {
8133 return false;
8134 }
8135 return true;
8136}
8137
Ted Kremenek6865f772011-08-18 20:55:45 +00008138// Warn if the user has made the 'size' argument to strlcpy or strlcat
8139// be the size of the source, instead of the destination.
8140void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8141 IdentifierInfo *FnName) {
8142
8143 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00008144 unsigned NumArgs = Call->getNumArgs();
8145 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00008146 return;
8147
8148 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8149 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00008150 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00008151
8152 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8153 Call->getLocStart(), Call->getRParenLoc()))
8154 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008155
8156 // Look for 'strlcpy(dst, x, sizeof(x))'
8157 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8158 CompareWithSrc = Ex;
8159 else {
8160 // Look for 'strlcpy(dst, x, strlen(x))'
8161 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008162 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8163 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008164 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8165 }
8166 }
8167
8168 if (!CompareWithSrc)
8169 return;
8170
8171 // Determine if the argument to sizeof/strlen is equal to the source
8172 // argument. In principle there's all kinds of things you could do
8173 // here, for instance creating an == expression and evaluating it with
8174 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8175 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8176 if (!SrcArgDRE)
8177 return;
8178
8179 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8180 if (!CompareWithSrcDRE ||
8181 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8182 return;
8183
8184 const Expr *OriginalSizeArg = Call->getArg(2);
8185 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8186 << OriginalSizeArg->getSourceRange() << FnName;
8187
8188 // Output a FIXIT hint if the destination is an array (rather than a
8189 // pointer to an array). This could be enhanced to handle some
8190 // pointers if we know the actual size, like if DstArg is 'array+2'
8191 // we could say 'sizeof(array)-2'.
8192 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008193 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008194 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008195
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008196 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008197 llvm::raw_svector_ostream OS(sizeString);
8198 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008199 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008200 OS << ")";
8201
8202 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8203 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8204 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008205}
8206
Anna Zaks314cd092012-02-01 19:08:57 +00008207/// Check if two expressions refer to the same declaration.
8208static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8209 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8210 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8211 return D1->getDecl() == D2->getDecl();
8212 return false;
8213}
8214
8215static const Expr *getStrlenExprArg(const Expr *E) {
8216 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8217 const FunctionDecl *FD = CE->getDirectCallee();
8218 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008219 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008220 return CE->getArg(0)->IgnoreParenCasts();
8221 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008222 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008223}
8224
8225// Warn on anti-patterns as the 'size' argument to strncat.
8226// The correct size argument should look like following:
8227// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8228void Sema::CheckStrncatArguments(const CallExpr *CE,
8229 IdentifierInfo *FnName) {
8230 // Don't crash if the user has the wrong number of arguments.
8231 if (CE->getNumArgs() < 3)
8232 return;
8233 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8234 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8235 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8236
Nico Weber0e6daef2013-12-26 23:38:39 +00008237 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8238 CE->getRParenLoc()))
8239 return;
8240
Anna Zaks314cd092012-02-01 19:08:57 +00008241 // Identify common expressions, which are wrongly used as the size argument
8242 // to strncat and may lead to buffer overflows.
8243 unsigned PatternType = 0;
8244 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8245 // - sizeof(dst)
8246 if (referToTheSameDecl(SizeOfArg, DstArg))
8247 PatternType = 1;
8248 // - sizeof(src)
8249 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8250 PatternType = 2;
8251 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8252 if (BE->getOpcode() == BO_Sub) {
8253 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8254 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8255 // - sizeof(dst) - strlen(dst)
8256 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8257 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8258 PatternType = 1;
8259 // - sizeof(src) - (anything)
8260 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8261 PatternType = 2;
8262 }
8263 }
8264
8265 if (PatternType == 0)
8266 return;
8267
Anna Zaks5069aa32012-02-03 01:27:37 +00008268 // Generate the diagnostic.
8269 SourceLocation SL = LenArg->getLocStart();
8270 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008271 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008272
8273 // If the function is defined as a builtin macro, do not show macro expansion.
8274 if (SM.isMacroArgExpansion(SL)) {
8275 SL = SM.getSpellingLoc(SL);
8276 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8277 SM.getSpellingLoc(SR.getEnd()));
8278 }
8279
Anna Zaks13b08572012-08-08 21:42:23 +00008280 // Check if the destination is an array (rather than a pointer to an array).
8281 QualType DstTy = DstArg->getType();
8282 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8283 Context);
8284 if (!isKnownSizeArray) {
8285 if (PatternType == 1)
8286 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8287 else
8288 Diag(SL, diag::warn_strncat_src_size) << SR;
8289 return;
8290 }
8291
Anna Zaks314cd092012-02-01 19:08:57 +00008292 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008293 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008294 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008295 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008296
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008297 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008298 llvm::raw_svector_ostream OS(sizeString);
8299 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008300 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008301 OS << ") - ";
8302 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008303 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008304 OS << ") - 1";
8305
Anna Zaks5069aa32012-02-03 01:27:37 +00008306 Diag(SL, diag::note_strncat_wrong_size)
8307 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008308}
8309
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008310//===--- CHECK: Return Address of Stack Variable --------------------------===//
8311
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008312static const Expr *EvalVal(const Expr *E,
8313 SmallVectorImpl<const DeclRefExpr *> &refVars,
8314 const Decl *ParentDecl);
8315static const Expr *EvalAddr(const Expr *E,
8316 SmallVectorImpl<const DeclRefExpr *> &refVars,
8317 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008318
8319/// CheckReturnStackAddr - Check if a return statement returns the address
8320/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008321static void
8322CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8323 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008324 const Expr *stackE = nullptr;
8325 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008326
8327 // Perform checking for returned stack addresses, local blocks,
8328 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008329 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008330 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008331 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008332 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008333 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008334 }
8335
Craig Topperc3ec1492014-05-26 06:22:03 +00008336 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008337 return; // Nothing suspicious was found.
8338
Simon Pilgrim750bde62017-03-31 11:00:53 +00008339 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008340 // of a parameter reference doesn't need a warning.
8341 for (auto *DRE : refVars)
8342 if (isa<ParmVarDecl>(DRE->getDecl()))
8343 return;
8344
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008345 SourceLocation diagLoc;
8346 SourceRange diagRange;
8347 if (refVars.empty()) {
8348 diagLoc = stackE->getLocStart();
8349 diagRange = stackE->getSourceRange();
8350 } else {
8351 // We followed through a reference variable. 'stackE' contains the
8352 // problematic expression but we will warn at the return statement pointing
8353 // at the reference variable. We will later display the "trail" of
8354 // reference variables using notes.
8355 diagLoc = refVars[0]->getLocStart();
8356 diagRange = refVars[0]->getSourceRange();
8357 }
8358
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008359 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8360 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008361 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008362 << DR->getDecl()->getDeclName() << diagRange;
8363 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008364 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008365 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008366 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008367 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008368 // If there is an LValue->RValue conversion, then the value of the
8369 // reference type is used, not the reference.
8370 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8371 if (ICE->getCastKind() == CK_LValueToRValue) {
8372 return;
8373 }
8374 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008375 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8376 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008377 }
8378
8379 // Display the "trail" of reference variables that we followed until we
8380 // found the problematic expression using notes.
8381 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008382 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008383 // If this var binds to another reference var, show the range of the next
8384 // var, otherwise the var binds to the problematic expression, in which case
8385 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008386 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8387 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008388 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8389 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008390 }
8391}
8392
8393/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8394/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008395/// to a location on the stack, a local block, an address of a label, or a
8396/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008397/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008398/// encounter a subexpression that (1) clearly does not lead to one of the
8399/// above problematic expressions (2) is something we cannot determine leads to
8400/// a problematic expression based on such local checking.
8401///
8402/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8403/// the expression that they point to. Such variables are added to the
8404/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008405///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008406/// EvalAddr processes expressions that are pointers that are used as
8407/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008408/// At the base case of the recursion is a check for the above problematic
8409/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008410///
8411/// This implementation handles:
8412///
8413/// * pointer-to-pointer casts
8414/// * implicit conversions from array references to pointers
8415/// * taking the address of fields
8416/// * arbitrary interplay between "&" and "*" operators
8417/// * pointer arithmetic from an address of a stack variable
8418/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008419static const Expr *EvalAddr(const Expr *E,
8420 SmallVectorImpl<const DeclRefExpr *> &refVars,
8421 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008422 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008423 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008424
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008425 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008426 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008427 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008428 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008429 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008430
Peter Collingbourne91147592011-04-15 00:35:48 +00008431 E = E->IgnoreParens();
8432
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008433 // Our "symbolic interpreter" is just a dispatch off the currently
8434 // viewed AST node. We then recursively traverse the AST by calling
8435 // EvalAddr and EvalVal appropriately.
8436 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008437 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008438 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008439
Richard Smith40f08eb2014-01-30 22:05:38 +00008440 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008441 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008442 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008443
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008444 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008445 // If this is a reference variable, follow through to the expression that
8446 // it points to.
8447 if (V->hasLocalStorage() &&
8448 V->getType()->isReferenceType() && V->hasInit()) {
8449 // Add the reference variable to the "trail".
8450 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008451 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008452 }
8453
Craig Topperc3ec1492014-05-26 06:22:03 +00008454 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008455 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008456
Chris Lattner934edb22007-12-28 05:31:15 +00008457 case Stmt::UnaryOperatorClass: {
8458 // The only unary operator that make sense to handle here
8459 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008460 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008461
John McCalle3027922010-08-25 11:45:40 +00008462 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008463 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008464 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008465 }
Mike Stump11289f42009-09-09 15:08:12 +00008466
Chris Lattner934edb22007-12-28 05:31:15 +00008467 case Stmt::BinaryOperatorClass: {
8468 // Handle pointer arithmetic. All other binary operators are not valid
8469 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008470 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008471 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008472
John McCalle3027922010-08-25 11:45:40 +00008473 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008474 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008475
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008476 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008477
8478 // Determine which argument is the real pointer base. It could be
8479 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008480 if (!Base->getType()->isPointerType())
8481 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008482
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008483 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008484 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008485 }
Steve Naroff2752a172008-09-10 19:17:48 +00008486
Chris Lattner934edb22007-12-28 05:31:15 +00008487 // For conditional operators we need to see if either the LHS or RHS are
8488 // valid DeclRefExpr*s. If one of them is valid, we return it.
8489 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008490 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008491
Chris Lattner934edb22007-12-28 05:31:15 +00008492 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008493 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008494 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008495 // In C++, we can have a throw-expression, which has 'void' type.
8496 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008497 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008498 return LHS;
8499 }
Chris Lattner934edb22007-12-28 05:31:15 +00008500
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008501 // In C++, we can have a throw-expression, which has 'void' type.
8502 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008503 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008504
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008505 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008506 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008507
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008508 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008509 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008510 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008511 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008512
8513 case Stmt::AddrLabelExprClass:
8514 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008515
John McCall28fc7092011-11-10 05:35:25 +00008516 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008517 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8518 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008519
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008520 // For casts, we need to handle conversions from arrays to
8521 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008522 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008523 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008524 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008525 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008526 case Stmt::CXXStaticCastExprClass:
8527 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008528 case Stmt::CXXConstCastExprClass:
8529 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008530 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008531 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008532 case CK_LValueToRValue:
8533 case CK_NoOp:
8534 case CK_BaseToDerived:
8535 case CK_DerivedToBase:
8536 case CK_UncheckedDerivedToBase:
8537 case CK_Dynamic:
8538 case CK_CPointerToObjCPointerCast:
8539 case CK_BlockPointerToObjCPointerCast:
8540 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008541 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008542
8543 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008544 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008545
Richard Trieudadefde2014-07-02 04:39:38 +00008546 case CK_BitCast:
8547 if (SubExpr->getType()->isAnyPointerType() ||
8548 SubExpr->getType()->isBlockPointerType() ||
8549 SubExpr->getType()->isObjCQualifiedIdType())
8550 return EvalAddr(SubExpr, refVars, ParentDecl);
8551 else
8552 return nullptr;
8553
Eli Friedman8195ad72012-02-23 23:04:32 +00008554 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008555 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008556 }
Chris Lattner934edb22007-12-28 05:31:15 +00008557 }
Mike Stump11289f42009-09-09 15:08:12 +00008558
Douglas Gregorfe314812011-06-21 17:03:29 +00008559 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008560 if (const Expr *Result =
8561 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8562 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008563 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008564 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008565
Chris Lattner934edb22007-12-28 05:31:15 +00008566 // Everything else: we simply don't reason about them.
8567 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008568 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008569 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008570}
Mike Stump11289f42009-09-09 15:08:12 +00008571
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008572/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8573/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008574static const Expr *EvalVal(const Expr *E,
8575 SmallVectorImpl<const DeclRefExpr *> &refVars,
8576 const Decl *ParentDecl) {
8577 do {
8578 // We should only be called for evaluating non-pointer expressions, or
8579 // expressions with a pointer type that are not used as references but
8580 // instead
8581 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008582
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008583 // Our "symbolic interpreter" is just a dispatch off the currently
8584 // viewed AST node. We then recursively traverse the AST by calling
8585 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008586
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008587 E = E->IgnoreParens();
8588 switch (E->getStmtClass()) {
8589 case Stmt::ImplicitCastExprClass: {
8590 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8591 if (IE->getValueKind() == VK_LValue) {
8592 E = IE->getSubExpr();
8593 continue;
8594 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008595 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008596 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008597
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008598 case Stmt::ExprWithCleanupsClass:
8599 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8600 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008601
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008602 case Stmt::DeclRefExprClass: {
8603 // When we hit a DeclRefExpr we are looking at code that refers to a
8604 // variable's name. If it's not a reference variable we check if it has
8605 // local storage within the function, and if so, return the expression.
8606 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8607
8608 // If we leave the immediate function, the lifetime isn't about to end.
8609 if (DR->refersToEnclosingVariableOrCapture())
8610 return nullptr;
8611
8612 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8613 // Check if it refers to itself, e.g. "int& i = i;".
8614 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008615 return DR;
8616
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008617 if (V->hasLocalStorage()) {
8618 if (!V->getType()->isReferenceType())
8619 return DR;
8620
8621 // Reference variable, follow through to the expression that
8622 // it points to.
8623 if (V->hasInit()) {
8624 // Add the reference variable to the "trail".
8625 refVars.push_back(DR);
8626 return EvalVal(V->getInit(), refVars, V);
8627 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008628 }
8629 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008630
8631 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008632 }
Mike Stump11289f42009-09-09 15:08:12 +00008633
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008634 case Stmt::UnaryOperatorClass: {
8635 // The only unary operator that make sense to handle here
8636 // is Deref. All others don't resolve to a "name." This includes
8637 // handling all sorts of rvalues passed to a unary operator.
8638 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008639
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008640 if (U->getOpcode() == UO_Deref)
8641 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008642
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008643 return nullptr;
8644 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008645
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008646 case Stmt::ArraySubscriptExprClass: {
8647 // Array subscripts are potential references to data on the stack. We
8648 // retrieve the DeclRefExpr* for the array variable if it indeed
8649 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008650 const auto *ASE = cast<ArraySubscriptExpr>(E);
8651 if (ASE->isTypeDependent())
8652 return nullptr;
8653 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008654 }
Mike Stump11289f42009-09-09 15:08:12 +00008655
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008656 case Stmt::OMPArraySectionExprClass: {
8657 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8658 ParentDecl);
8659 }
Mike Stump11289f42009-09-09 15:08:12 +00008660
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008661 case Stmt::ConditionalOperatorClass: {
8662 // For conditional operators we need to see if either the LHS or RHS are
8663 // non-NULL Expr's. If one is non-NULL, we return it.
8664 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008665
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008666 // Handle the GNU extension for missing LHS.
8667 if (const Expr *LHSExpr = C->getLHS()) {
8668 // In C++, we can have a throw-expression, which has 'void' type.
8669 if (!LHSExpr->getType()->isVoidType())
8670 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8671 return LHS;
8672 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008673
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008674 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008675 if (C->getRHS()->getType()->isVoidType())
8676 return nullptr;
8677
8678 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008679 }
8680
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008681 // Accesses to members are potential references to data on the stack.
8682 case Stmt::MemberExprClass: {
8683 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008684
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008685 // Check for indirect access. We only want direct field accesses.
8686 if (M->isArrow())
8687 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008688
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008689 // Check whether the member type is itself a reference, in which case
8690 // we're not going to refer to the member, but to what the member refers
8691 // to.
8692 if (M->getMemberDecl()->getType()->isReferenceType())
8693 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008694
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008695 return EvalVal(M->getBase(), refVars, ParentDecl);
8696 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008697
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008698 case Stmt::MaterializeTemporaryExprClass:
8699 if (const Expr *Result =
8700 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8701 refVars, ParentDecl))
8702 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008703 return E;
8704
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008705 default:
8706 // Check that we don't return or take the address of a reference to a
8707 // temporary. This is only useful in C++.
8708 if (!E->isTypeDependent() && E->isRValue())
8709 return E;
8710
8711 // Everything else: we simply don't reason about them.
8712 return nullptr;
8713 }
8714 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008715}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008716
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008717void
8718Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8719 SourceLocation ReturnLoc,
8720 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008721 const AttrVec *Attrs,
8722 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008723 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8724
8725 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008726 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8727 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008728 CheckNonNullExpr(*this, RetValExp))
8729 Diag(ReturnLoc, diag::warn_null_ret)
8730 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008731
8732 // C++11 [basic.stc.dynamic.allocation]p4:
8733 // If an allocation function declared with a non-throwing
8734 // exception-specification fails to allocate storage, it shall return
8735 // a null pointer. Any other allocation function that fails to allocate
8736 // storage shall indicate failure only by throwing an exception [...]
8737 if (FD) {
8738 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8739 if (Op == OO_New || Op == OO_Array_New) {
8740 const FunctionProtoType *Proto
8741 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008742 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008743 CheckNonNullExpr(*this, RetValExp))
8744 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8745 << FD << getLangOpts().CPlusPlus11;
8746 }
8747 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008748}
8749
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008750//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8751
8752/// Check for comparisons of floating point operands using != and ==.
8753/// Issue a warning if these are no self-comparisons, as they are not likely
8754/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008755void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008756 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8757 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008758
8759 // Special case: check for x == x (which is OK).
8760 // Do not emit warnings for such cases.
8761 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8762 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8763 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008764 return;
Mike Stump11289f42009-09-09 15:08:12 +00008765
Ted Kremenekeda40e22007-11-29 00:59:04 +00008766 // Special case: check for comparisons against literals that can be exactly
8767 // represented by APFloat. In such cases, do not emit a warning. This
8768 // is a heuristic: often comparison against such literals are used to
8769 // detect if a value in a variable has not changed. This clearly can
8770 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008771 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8772 if (FLL->isExact())
8773 return;
8774 } else
8775 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8776 if (FLR->isExact())
8777 return;
Mike Stump11289f42009-09-09 15:08:12 +00008778
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008779 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008780 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008781 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008782 return;
Mike Stump11289f42009-09-09 15:08:12 +00008783
David Blaikie1f4ff152012-07-16 20:47:22 +00008784 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008785 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008786 return;
Mike Stump11289f42009-09-09 15:08:12 +00008787
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008788 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008789 Diag(Loc, diag::warn_floatingpoint_eq)
8790 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008791}
John McCallca01b222010-01-04 23:21:16 +00008792
John McCall70aa5392010-01-06 05:24:50 +00008793//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8794//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008795
John McCall70aa5392010-01-06 05:24:50 +00008796namespace {
John McCallca01b222010-01-04 23:21:16 +00008797
John McCall70aa5392010-01-06 05:24:50 +00008798/// Structure recording the 'active' range of an integer-valued
8799/// expression.
8800struct IntRange {
8801 /// The number of bits active in the int.
8802 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008803
John McCall70aa5392010-01-06 05:24:50 +00008804 /// True if the int is known not to have negative values.
8805 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008806
John McCall70aa5392010-01-06 05:24:50 +00008807 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008808 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008809
John McCall817d4af2010-11-10 23:38:19 +00008810 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008811 static IntRange forBoolType() {
8812 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008813 }
8814
John McCall817d4af2010-11-10 23:38:19 +00008815 /// Returns the range of an opaque value of the given integral type.
8816 static IntRange forValueOfType(ASTContext &C, QualType T) {
8817 return forValueOfCanonicalType(C,
8818 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008819 }
8820
John McCall817d4af2010-11-10 23:38:19 +00008821 /// Returns the range of an opaque value of a canonical integral type.
8822 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008823 assert(T->isCanonicalUnqualified());
8824
8825 if (const VectorType *VT = dyn_cast<VectorType>(T))
8826 T = VT->getElementType().getTypePtr();
8827 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8828 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008829 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8830 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008831
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008832 if (!C.getLangOpts().CPlusPlus) {
8833 // For enum types in C code, use the underlying datatype.
8834 if (const EnumType *ET = dyn_cast<EnumType>(T))
8835 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8836 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8837 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008838 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008839 // In C++11, enums can have a fixed underlying type. Use this type to
8840 // compute the range.
8841 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008842 return IntRange(C.getIntWidth(QualType(T, 0)),
8843 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008844 }
John McCall18a2c2c2010-11-09 22:22:12 +00008845
David Majnemer6a426652013-06-07 22:07:20 +00008846 unsigned NumPositive = Enum->getNumPositiveBits();
8847 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008848
David Majnemer6a426652013-06-07 22:07:20 +00008849 if (NumNegative == 0)
8850 return IntRange(NumPositive, true/*NonNegative*/);
8851 else
8852 return IntRange(std::max(NumPositive + 1, NumNegative),
8853 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008854 }
John McCall70aa5392010-01-06 05:24:50 +00008855
8856 const BuiltinType *BT = cast<BuiltinType>(T);
8857 assert(BT->isInteger());
8858
8859 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8860 }
8861
John McCall817d4af2010-11-10 23:38:19 +00008862 /// Returns the "target" range of a canonical integral type, i.e.
8863 /// the range of values expressible in the type.
8864 ///
8865 /// This matches forValueOfCanonicalType except that enums have the
8866 /// full range of their type, not the range of their enumerators.
8867 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8868 assert(T->isCanonicalUnqualified());
8869
8870 if (const VectorType *VT = dyn_cast<VectorType>(T))
8871 T = VT->getElementType().getTypePtr();
8872 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8873 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008874 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8875 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008876 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008877 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008878
8879 const BuiltinType *BT = cast<BuiltinType>(T);
8880 assert(BT->isInteger());
8881
8882 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8883 }
8884
8885 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008886 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008887 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008888 L.NonNegative && R.NonNegative);
8889 }
8890
John McCall817d4af2010-11-10 23:38:19 +00008891 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008892 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008893 return IntRange(std::min(L.Width, R.Width),
8894 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008895 }
8896};
8897
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008898} // namespace
8899
8900static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8901 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008902 if (value.isSigned() && value.isNegative())
8903 return IntRange(value.getMinSignedBits(), false);
8904
8905 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008906 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008907
8908 // isNonNegative() just checks the sign bit without considering
8909 // signedness.
8910 return IntRange(value.getActiveBits(), true);
8911}
8912
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008913static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8914 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008915 if (result.isInt())
8916 return GetValueRange(C, result.getInt(), MaxWidth);
8917
8918 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008919 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8920 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8921 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8922 R = IntRange::join(R, El);
8923 }
John McCall70aa5392010-01-06 05:24:50 +00008924 return R;
8925 }
8926
8927 if (result.isComplexInt()) {
8928 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8929 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8930 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008931 }
8932
8933 // This can happen with lossless casts to intptr_t of "based" lvalues.
8934 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008935 // FIXME: The only reason we need to pass the type in here is to get
8936 // the sign right on this one case. It would be nice if APValue
8937 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008938 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008939 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008940}
John McCall70aa5392010-01-06 05:24:50 +00008941
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008942static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008943 QualType Ty = E->getType();
8944 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8945 Ty = AtomicRHS->getValueType();
8946 return Ty;
8947}
8948
John McCall70aa5392010-01-06 05:24:50 +00008949/// Pseudo-evaluate the given integer expression, estimating the
8950/// range of values it might take.
8951///
8952/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008953static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008954 E = E->IgnoreParens();
8955
8956 // Try a full evaluation first.
8957 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008958 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008959 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008960
8961 // I think we only want to look through implicit casts here; if the
8962 // user has an explicit widening cast, we should treat the value as
8963 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008964 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008965 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008966 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8967
Eli Friedmane6d33952013-07-08 20:20:06 +00008968 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008969
George Burgess IVdf1ed002016-01-13 01:52:39 +00008970 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8971 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008972
John McCall70aa5392010-01-06 05:24:50 +00008973 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008974 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008975 return OutputTypeRange;
8976
8977 IntRange SubRange
8978 = GetExprRange(C, CE->getSubExpr(),
8979 std::min(MaxWidth, OutputTypeRange.Width));
8980
8981 // Bail out if the subexpr's range is as wide as the cast type.
8982 if (SubRange.Width >= OutputTypeRange.Width)
8983 return OutputTypeRange;
8984
8985 // Otherwise, we take the smaller width, and we're non-negative if
8986 // either the output type or the subexpr is.
8987 return IntRange(SubRange.Width,
8988 SubRange.NonNegative || OutputTypeRange.NonNegative);
8989 }
8990
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008991 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008992 // If we can fold the condition, just take that operand.
8993 bool CondResult;
8994 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8995 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8996 : CO->getFalseExpr(),
8997 MaxWidth);
8998
8999 // Otherwise, conservatively merge.
9000 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9001 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9002 return IntRange::join(L, R);
9003 }
9004
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009005 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009006 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00009007 case BO_Cmp:
9008 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00009009
9010 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00009011 case BO_LAnd:
9012 case BO_LOr:
9013 case BO_LT:
9014 case BO_GT:
9015 case BO_LE:
9016 case BO_GE:
9017 case BO_EQ:
9018 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009019 return IntRange::forBoolType();
9020
John McCallc3688382011-07-13 06:35:24 +00009021 // The type of the assignments is the type of the LHS, so the RHS
9022 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009023 case BO_MulAssign:
9024 case BO_DivAssign:
9025 case BO_RemAssign:
9026 case BO_AddAssign:
9027 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009028 case BO_XorAssign:
9029 case BO_OrAssign:
9030 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009031 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009032
John McCallc3688382011-07-13 06:35:24 +00009033 // Simple assignments just pass through the RHS, which will have
9034 // been coerced to the LHS type.
9035 case BO_Assign:
9036 // TODO: bitfields?
9037 return GetExprRange(C, BO->getRHS(), MaxWidth);
9038
John McCall70aa5392010-01-06 05:24:50 +00009039 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009040 case BO_PtrMemD:
9041 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009042 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009043
John McCall2ce81ad2010-01-06 22:07:33 +00009044 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009045 case BO_And:
9046 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009047 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9048 GetExprRange(C, BO->getRHS(), MaxWidth));
9049
John McCall70aa5392010-01-06 05:24:50 +00009050 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00009051 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00009052 // ...except that we want to treat '1 << (blah)' as logically
9053 // positive. It's an important idiom.
9054 if (IntegerLiteral *I
9055 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9056 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009057 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00009058 return IntRange(R.Width, /*NonNegative*/ true);
9059 }
9060 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009061 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00009062
John McCalle3027922010-08-25 11:45:40 +00009063 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00009064 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009065
John McCall2ce81ad2010-01-06 22:07:33 +00009066 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009067 case BO_Shr:
9068 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009069 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9070
9071 // If the shift amount is a positive constant, drop the width by
9072 // that much.
9073 llvm::APSInt shift;
9074 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9075 shift.isNonNegative()) {
9076 unsigned zext = shift.getZExtValue();
9077 if (zext >= L.Width)
9078 L.Width = (L.NonNegative ? 0 : 1);
9079 else
9080 L.Width -= zext;
9081 }
9082
9083 return L;
9084 }
9085
9086 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009087 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009088 return GetExprRange(C, BO->getRHS(), MaxWidth);
9089
John McCall2ce81ad2010-01-06 22:07:33 +00009090 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009091 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009092 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009093 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009094 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009095
John McCall51431812011-07-14 22:39:48 +00009096 // The width of a division result is mostly determined by the size
9097 // of the LHS.
9098 case BO_Div: {
9099 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009100 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009101 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9102
9103 // If the divisor is constant, use that.
9104 llvm::APSInt divisor;
9105 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9106 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9107 if (log2 >= L.Width)
9108 L.Width = (L.NonNegative ? 0 : 1);
9109 else
9110 L.Width = std::min(L.Width - log2, MaxWidth);
9111 return L;
9112 }
9113
9114 // Otherwise, just use the LHS's width.
9115 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9116 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9117 }
9118
9119 // The result of a remainder can't be larger than the result of
9120 // either side.
9121 case BO_Rem: {
9122 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009123 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009124 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9125 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9126
9127 IntRange meet = IntRange::meet(L, R);
9128 meet.Width = std::min(meet.Width, MaxWidth);
9129 return meet;
9130 }
9131
9132 // The default behavior is okay for these.
9133 case BO_Mul:
9134 case BO_Add:
9135 case BO_Xor:
9136 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009137 break;
9138 }
9139
John McCall51431812011-07-14 22:39:48 +00009140 // The default case is to treat the operation as if it were closed
9141 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009142 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9143 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9144 return IntRange::join(L, R);
9145 }
9146
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009147 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009148 switch (UO->getOpcode()) {
9149 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009150 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009151 return IntRange::forBoolType();
9152
9153 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009154 case UO_Deref:
9155 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009156 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009157
9158 default:
9159 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9160 }
9161 }
9162
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009163 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009164 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9165
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009166 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009167 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009168 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009169
Eli Friedmane6d33952013-07-08 20:20:06 +00009170 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009171}
John McCall263a48b2010-01-04 23:31:57 +00009172
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009173static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009174 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009175}
9176
John McCall263a48b2010-01-04 23:31:57 +00009177/// Checks whether the given value, which currently has the given
9178/// source semantics, has the same value when coerced through the
9179/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009180static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9181 const llvm::fltSemantics &Src,
9182 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009183 llvm::APFloat truncated = value;
9184
9185 bool ignored;
9186 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9187 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9188
9189 return truncated.bitwiseIsEqual(value);
9190}
9191
9192/// Checks whether the given value, which currently has the given
9193/// source semantics, has the same value when coerced through the
9194/// target semantics.
9195///
9196/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009197static bool IsSameFloatAfterCast(const APValue &value,
9198 const llvm::fltSemantics &Src,
9199 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009200 if (value.isFloat())
9201 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9202
9203 if (value.isVector()) {
9204 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9205 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9206 return false;
9207 return true;
9208 }
9209
9210 assert(value.isComplexFloat());
9211 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9212 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9213}
9214
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009215static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009216
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009217static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009218 // Suppress cases where we are comparing against an enum constant.
9219 if (const DeclRefExpr *DR =
9220 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9221 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009222 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009223
9224 // Suppress cases where the '0' value is expanded from a macro.
9225 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009226 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009227
Roman Lebedev6de129e2017-10-15 20:13:17 +00009228 return false;
9229}
9230
Richard Smith692f66ab2017-12-06 19:23:19 +00009231static bool isKnownToHaveUnsignedValue(Expr *E) {
9232 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009233 (!E->getType()->isSignedIntegerType() ||
9234 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9235}
9236
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009237namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009238/// The promoted range of values of a type. In general this has the
9239/// following structure:
9240///
9241/// |-----------| . . . |-----------|
9242/// ^ ^ ^ ^
9243/// Min HoleMin HoleMax Max
9244///
9245/// ... where there is only a hole if a signed type is promoted to unsigned
9246/// (in which case Min and Max are the smallest and largest representable
9247/// values).
9248struct PromotedRange {
9249 // Min, or HoleMax if there is a hole.
9250 llvm::APSInt PromotedMin;
9251 // Max, or HoleMin if there is a hole.
9252 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009253
Richard Smitha5370fb2017-12-08 22:57:11 +00009254 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9255 if (R.Width == 0)
9256 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9257 else if (R.Width >= BitWidth && !Unsigned) {
9258 // Promotion made the type *narrower*. This happens when promoting
9259 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9260 // Treat all values of 'signed int' as being in range for now.
9261 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9262 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9263 } else {
9264 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9265 .extOrTrunc(BitWidth);
9266 PromotedMin.setIsUnsigned(Unsigned);
9267
9268 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9269 .extOrTrunc(BitWidth);
9270 PromotedMax.setIsUnsigned(Unsigned);
9271 }
9272 }
9273
9274 // Determine whether this range is contiguous (has no hole).
9275 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9276
9277 // Where a constant value is within the range.
9278 enum ComparisonResult {
9279 LT = 0x1,
9280 LE = 0x2,
9281 GT = 0x4,
9282 GE = 0x8,
9283 EQ = 0x10,
9284 NE = 0x20,
9285 InRangeFlag = 0x40,
9286
9287 Less = LE | LT | NE,
9288 Min = LE | InRangeFlag,
9289 InRange = InRangeFlag,
9290 Max = GE | InRangeFlag,
9291 Greater = GE | GT | NE,
9292
9293 OnlyValue = LE | GE | EQ | InRangeFlag,
9294 InHole = NE
9295 };
9296
9297 ComparisonResult compare(const llvm::APSInt &Value) const {
9298 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9299 Value.isUnsigned() == PromotedMin.isUnsigned());
9300 if (!isContiguous()) {
9301 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9302 if (Value.isMinValue()) return Min;
9303 if (Value.isMaxValue()) return Max;
9304 if (Value >= PromotedMin) return InRange;
9305 if (Value <= PromotedMax) return InRange;
9306 return InHole;
9307 }
9308
9309 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9310 case -1: return Less;
9311 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9312 case 1:
9313 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9314 case -1: return InRange;
9315 case 0: return Max;
9316 case 1: return Greater;
9317 }
9318 }
9319
9320 llvm_unreachable("impossible compare result");
9321 }
9322
Richard Smithc70f1d62017-12-14 15:16:18 +00009323 static llvm::Optional<StringRef>
9324 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9325 if (Op == BO_Cmp) {
9326 ComparisonResult LTFlag = LT, GTFlag = GT;
9327 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9328
9329 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9330 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9331 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9332 return llvm::None;
9333 }
9334
Richard Smitha5370fb2017-12-08 22:57:11 +00009335 ComparisonResult TrueFlag, FalseFlag;
9336 if (Op == BO_EQ) {
9337 TrueFlag = EQ;
9338 FalseFlag = NE;
9339 } else if (Op == BO_NE) {
9340 TrueFlag = NE;
9341 FalseFlag = EQ;
9342 } else {
9343 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9344 TrueFlag = LT;
9345 FalseFlag = GE;
9346 } else {
9347 TrueFlag = GT;
9348 FalseFlag = LE;
9349 }
9350 if (Op == BO_GE || Op == BO_LE)
9351 std::swap(TrueFlag, FalseFlag);
9352 }
9353 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009354 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009355 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009356 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009357 return llvm::None;
9358 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009359};
John McCallcc7e5bf2010-05-06 08:58:33 +00009360}
9361
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009362static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009363 // Strip off implicit integral promotions.
9364 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009365 if (ICE->getCastKind() != CK_IntegralCast &&
9366 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009367 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009368 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009369 }
9370
9371 return E->getType()->isEnumeralType();
9372}
9373
Richard Smith692f66ab2017-12-06 19:23:19 +00009374static int classifyConstantValue(Expr *Constant) {
9375 // The values of this enumeration are used in the diagnostics
9376 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9377 enum ConstantValueKind {
9378 Miscellaneous = 0,
9379 LiteralTrue,
9380 LiteralFalse
9381 };
9382 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9383 return BL->getValue() ? ConstantValueKind::LiteralTrue
9384 : ConstantValueKind::LiteralFalse;
9385 return ConstantValueKind::Miscellaneous;
9386}
9387
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009388static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9389 Expr *Constant, Expr *Other,
9390 const llvm::APSInt &Value,
9391 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009392 if (S.inTemplateInstantiation())
9393 return false;
9394
Richard Smitha5370fb2017-12-08 22:57:11 +00009395 Expr *OriginalOther = Other;
9396
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009397 Constant = Constant->IgnoreParenImpCasts();
9398 Other = Other->IgnoreParenImpCasts();
9399
Richard Smitha5370fb2017-12-08 22:57:11 +00009400 // Suppress warnings on tautological comparisons between values of the same
9401 // enumeration type. There are only two ways we could warn on this:
9402 // - If the constant is outside the range of representable values of
9403 // the enumeration. In such a case, we should warn about the cast
9404 // to enumeration type, not about the comparison.
9405 // - If the constant is the maximum / minimum in-range value. For an
9406 // enumeratin type, such comparisons can be meaningful and useful.
9407 if (Constant->getType()->isEnumeralType() &&
9408 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9409 return false;
9410
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009411 // TODO: Investigate using GetExprRange() to get tighter bounds
9412 // on the bit ranges.
9413 QualType OtherT = Other->getType();
9414 if (const auto *AT = OtherT->getAs<AtomicType>())
9415 OtherT = AT->getValueType();
9416 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9417
9418 // Whether we're treating Other as being a bool because of the form of
9419 // expression despite it having another type (typically 'int' in C).
9420 bool OtherIsBooleanDespiteType =
9421 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9422 if (OtherIsBooleanDespiteType)
9423 OtherRange = IntRange::forBoolType();
9424
Richard Smitha5370fb2017-12-08 22:57:11 +00009425 // Determine the promoted range of the other type and see if a comparison of
9426 // the constant against that range is tautological.
9427 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9428 Value.isUnsigned());
9429 auto Cmp = OtherPromotedRange.compare(Value);
9430 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9431 if (!Result)
9432 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009433
Richard Smitha5370fb2017-12-08 22:57:11 +00009434 // Suppress the diagnostic for an in-range comparison if the constant comes
9435 // from a macro or enumerator. We don't want to diagnose
9436 //
9437 // some_long_value <= INT_MAX
9438 //
9439 // when sizeof(int) == sizeof(long).
9440 bool InRange = Cmp & PromotedRange::InRangeFlag;
9441 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9442 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009443
9444 // If this is a comparison to an enum constant, include that
9445 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009446 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009447 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9448 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9449
Richard Smitha5370fb2017-12-08 22:57:11 +00009450 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009451 SmallString<64> PrettySourceValue;
9452 llvm::raw_svector_ostream OS(PrettySourceValue);
9453 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009454 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009455 else
9456 OS << Value;
9457
Richard Smitha5370fb2017-12-08 22:57:11 +00009458 // FIXME: We use a somewhat different formatting for the in-range cases and
9459 // cases involving boolean values for historical reasons. We should pick a
9460 // consistent way of presenting these diagnostics.
9461 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9462 S.DiagRuntimeBehavior(
9463 E->getOperatorLoc(), E,
9464 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9465 : diag::warn_tautological_bool_compare)
9466 << OS.str() << classifyConstantValue(Constant)
9467 << OtherT << OtherIsBooleanDespiteType << *Result
9468 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9469 } else {
9470 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9471 ? (HasEnumType(OriginalOther)
9472 ? diag::warn_unsigned_enum_always_true_comparison
9473 : diag::warn_unsigned_always_true_comparison)
9474 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009475
Richard Smitha5370fb2017-12-08 22:57:11 +00009476 S.Diag(E->getOperatorLoc(), Diag)
9477 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9478 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9479 }
9480
9481 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009482}
9483
John McCallcc7e5bf2010-05-06 08:58:33 +00009484/// Analyze the operands of the given comparison. Implements the
9485/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009486static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009487 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9488 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009489}
John McCall263a48b2010-01-04 23:31:57 +00009490
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009491/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009492///
Richard Trieu82402a02011-09-15 21:56:47 +00009493/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009494static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009495 // The type the comparison is being performed in.
9496 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009497
9498 // Only analyze comparison operators where both sides have been converted to
9499 // the same type.
9500 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9501 return AnalyzeImpConvsInComparison(S, E);
9502
9503 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009504 if (E->isValueDependent())
9505 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009506
Roman Lebedev6de129e2017-10-15 20:13:17 +00009507 Expr *LHS = E->getLHS();
9508 Expr *RHS = E->getRHS();
9509
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009510 if (T->isIntegralType(S.Context)) {
9511 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009512 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009513
Roman Lebedev6de129e2017-10-15 20:13:17 +00009514 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9515 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009516
Roman Lebedev6de129e2017-10-15 20:13:17 +00009517 // We don't care about expressions whose result is a constant.
9518 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9519 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009520
Roman Lebedev6de129e2017-10-15 20:13:17 +00009521 // We only care about expressions where just one side is literal
9522 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9523 // Is the constant on the RHS or LHS?
9524 const bool RhsConstant = IsRHSIntegralLiteral;
9525 Expr *Const = RhsConstant ? RHS : LHS;
9526 Expr *Other = RhsConstant ? LHS : RHS;
9527 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9528
9529 // Check whether an integer constant comparison results in a value
9530 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009531 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9532 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009533 }
9534 }
9535
9536 if (!T->hasUnsignedIntegerRepresentation()) {
9537 // We don't do anything special if this isn't an unsigned integral
9538 // comparison: we're only interested in integral comparisons, and
9539 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009540 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009541 }
9542
9543 LHS = LHS->IgnoreParenImpCasts();
9544 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009545
Alex Lorenzb57409f2018-02-07 20:45:39 +00009546 if (!S.getLangOpts().CPlusPlus) {
9547 // Avoid warning about comparison of integers with different signs when
9548 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9549 // the type of `E`.
9550 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9551 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9552 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9553 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9554 }
9555
John McCallcc7e5bf2010-05-06 08:58:33 +00009556 // Check to see if one of the (unmodified) operands is of different
9557 // signedness.
9558 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009559 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9560 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009561 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009562 signedOperand = LHS;
9563 unsignedOperand = RHS;
9564 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9565 signedOperand = RHS;
9566 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009567 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009568 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009569 }
9570
John McCallcc7e5bf2010-05-06 08:58:33 +00009571 // Otherwise, calculate the effective range of the signed operand.
9572 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009573
John McCallcc7e5bf2010-05-06 08:58:33 +00009574 // Go ahead and analyze implicit conversions in the operands. Note
9575 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009576 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9577 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009578
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009579 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009580 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009581 return;
John McCallca01b222010-01-04 23:21:16 +00009582
9583 // For (in)equality comparisons, if the unsigned operand is a
9584 // constant which cannot collide with a overflowed signed operand,
9585 // then reinterpreting the signed operand as unsigned will not
9586 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009587 if (E->isEqualityOp()) {
9588 unsigned comparisonWidth = S.Context.getIntWidth(T);
9589 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009590
John McCallcc7e5bf2010-05-06 08:58:33 +00009591 // We should never be unable to prove that the unsigned operand is
9592 // non-negative.
9593 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9594
9595 if (unsignedRange.Width < comparisonWidth)
9596 return;
9597 }
9598
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009599 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9600 S.PDiag(diag::warn_mixed_sign_comparison)
9601 << LHS->getType() << RHS->getType()
9602 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009603}
9604
John McCall1f425642010-11-11 03:21:53 +00009605/// Analyzes an attempt to assign the given value to a bitfield.
9606///
9607/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009608static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9609 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009610 assert(Bitfield->isBitField());
9611 if (Bitfield->isInvalidDecl())
9612 return false;
9613
John McCalldeebbcf2010-11-11 05:33:51 +00009614 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009615 QualType BitfieldType = Bitfield->getType();
9616 if (BitfieldType->isBooleanType())
9617 return false;
9618
9619 if (BitfieldType->isEnumeralType()) {
9620 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9621 // If the underlying enum type was not explicitly specified as an unsigned
9622 // type and the enum contain only positive values, MSVC++ will cause an
9623 // inconsistency by storing this as a signed type.
9624 if (S.getLangOpts().CPlusPlus11 &&
9625 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9626 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9627 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9628 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9629 << BitfieldEnumDecl->getNameAsString();
9630 }
9631 }
9632
John McCalldeebbcf2010-11-11 05:33:51 +00009633 if (Bitfield->getType()->isBooleanType())
9634 return false;
9635
Douglas Gregor789adec2011-02-04 13:09:01 +00009636 // Ignore value- or type-dependent expressions.
9637 if (Bitfield->getBitWidth()->isValueDependent() ||
9638 Bitfield->getBitWidth()->isTypeDependent() ||
9639 Init->isValueDependent() ||
9640 Init->isTypeDependent())
9641 return false;
9642
John McCall1f425642010-11-11 03:21:53 +00009643 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009644 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009645
Richard Smith5fab0c92011-12-28 19:48:30 +00009646 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009647 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9648 Expr::SE_AllowSideEffects)) {
9649 // The RHS is not constant. If the RHS has an enum type, make sure the
9650 // bitfield is wide enough to hold all the values of the enum without
9651 // truncation.
9652 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9653 EnumDecl *ED = EnumTy->getDecl();
9654 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9655
9656 // Enum types are implicitly signed on Windows, so check if there are any
9657 // negative enumerators to see if the enum was intended to be signed or
9658 // not.
9659 bool SignedEnum = ED->getNumNegativeBits() > 0;
9660
9661 // Check for surprising sign changes when assigning enum values to a
9662 // bitfield of different signedness. If the bitfield is signed and we
9663 // have exactly the right number of bits to store this unsigned enum,
9664 // suggest changing the enum to an unsigned type. This typically happens
9665 // on Windows where unfixed enums always use an underlying type of 'int'.
9666 unsigned DiagID = 0;
9667 if (SignedEnum && !SignedBitfield) {
9668 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9669 } else if (SignedBitfield && !SignedEnum &&
9670 ED->getNumPositiveBits() == FieldWidth) {
9671 DiagID = diag::warn_signed_bitfield_enum_conversion;
9672 }
9673
9674 if (DiagID) {
9675 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9676 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9677 SourceRange TypeRange =
9678 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9679 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9680 << SignedEnum << TypeRange;
9681 }
9682
9683 // Compute the required bitwidth. If the enum has negative values, we need
9684 // one more bit than the normal number of positive bits to represent the
9685 // sign bit.
9686 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9687 ED->getNumNegativeBits())
9688 : ED->getNumPositiveBits();
9689
9690 // Check the bitwidth.
9691 if (BitsNeeded > FieldWidth) {
9692 Expr *WidthExpr = Bitfield->getBitWidth();
9693 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9694 << Bitfield << ED;
9695 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9696 << BitsNeeded << ED << WidthExpr->getSourceRange();
9697 }
9698 }
9699
John McCall1f425642010-11-11 03:21:53 +00009700 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009701 }
John McCall1f425642010-11-11 03:21:53 +00009702
John McCall1f425642010-11-11 03:21:53 +00009703 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009704
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009705 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009706 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009707 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9708 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009709
John McCall1f425642010-11-11 03:21:53 +00009710 if (OriginalWidth <= FieldWidth)
9711 return false;
9712
Eli Friedmanc267a322012-01-26 23:11:39 +00009713 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009714 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009715 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009716
Eli Friedmanc267a322012-01-26 23:11:39 +00009717 // Check whether the stored value is equal to the original value.
9718 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009719 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009720 return false;
9721
Eli Friedmanc267a322012-01-26 23:11:39 +00009722 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009723 // therefore don't strictly fit into a signed bitfield of width 1.
9724 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009725 return false;
9726
John McCall1f425642010-11-11 03:21:53 +00009727 std::string PrettyValue = Value.toString(10);
9728 std::string PrettyTrunc = TruncatedValue.toString(10);
9729
9730 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9731 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9732 << Init->getSourceRange();
9733
9734 return true;
9735}
9736
John McCalld2a53122010-11-09 23:24:47 +00009737/// Analyze the given simple or compound assignment for warning-worthy
9738/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009739static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009740 // Just recurse on the LHS.
9741 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9742
9743 // We want to recurse on the RHS as normal unless we're assigning to
9744 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009745 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009746 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009747 E->getOperatorLoc())) {
9748 // Recurse, ignoring any implicit conversions on the RHS.
9749 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9750 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009751 }
9752 }
9753
9754 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9755}
9756
John McCall263a48b2010-01-04 23:31:57 +00009757/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009758static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9759 SourceLocation CContext, unsigned diag,
9760 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009761 if (pruneControlFlow) {
9762 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9763 S.PDiag(diag)
9764 << SourceType << T << E->getSourceRange()
9765 << SourceRange(CContext));
9766 return;
9767 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009768 S.Diag(E->getExprLoc(), diag)
9769 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9770}
9771
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009772/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009773static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9774 SourceLocation CContext,
9775 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009776 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009777}
9778
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009779/// Analyze the given compound assignment for the possible losing of
9780/// floating-point precision.
9781static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9782 assert(isa<CompoundAssignOperator>(E) &&
9783 "Must be compound assignment operation");
9784 // Recurse on the LHS and RHS in here
9785 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9786 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9787
9788 // Now check the outermost expression
9789 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9790 const auto *RBT = cast<CompoundAssignOperator>(E)
9791 ->getComputationResultType()
9792 ->getAs<BuiltinType>();
9793
9794 // If both source and target are floating points.
9795 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9796 // Builtin FP kinds are ordered by increasing FP rank.
9797 if (ResultBT->getKind() < RBT->getKind())
9798 // We don't want to warn for system macro.
9799 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9800 // warn about dropping FP rank.
9801 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9802 E->getOperatorLoc(),
9803 diag::warn_impcast_float_result_precision);
9804}
Richard Trieube234c32016-04-21 21:04:55 +00009805
9806/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009807static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9808 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009809 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009810 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009811
9812 Expr *InnerE = E->IgnoreParenImpCasts();
9813 // We also want to warn on, e.g., "int i = -1.234"
9814 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9815 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9816 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9817
9818 const bool IsLiteral =
9819 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9820
9821 llvm::APFloat Value(0.0);
9822 bool IsConstant =
9823 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9824 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009825 return DiagnoseImpCast(S, E, T, CContext,
9826 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009827 }
9828
Chandler Carruth016ef402011-04-10 08:36:24 +00009829 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009830
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009831 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9832 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009833 llvm::APFloat::opStatus Result = Value.convertToInteger(
9834 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9835
9836 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009837 if (IsLiteral) return;
9838 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9839 PruneWarnings);
9840 }
9841
Erich Keanea4c48c62018-05-08 21:26:21 +00009842 // Conversion of a floating-point value to a non-bool integer where the
9843 // integral part cannot be represented by the integer type is undefined.
9844 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9845 return DiagnoseImpCast(
9846 S, E, T, CContext,
9847 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009848 : diag::warn_impcast_float_to_integer_out_of_range,
9849 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009850
Richard Trieube234c32016-04-21 21:04:55 +00009851 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009852 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009853 // Warn on floating point literal to integer.
9854 DiagID = diag::warn_impcast_literal_float_to_integer;
9855 } else if (IntegerValue == 0) {
9856 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9857 return DiagnoseImpCast(S, E, T, CContext,
9858 diag::warn_impcast_float_integer, PruneWarnings);
9859 }
9860 // Warn on non-zero to zero conversion.
9861 DiagID = diag::warn_impcast_float_to_integer_zero;
9862 } else {
9863 if (IntegerValue.isUnsigned()) {
9864 if (!IntegerValue.isMaxValue()) {
9865 return DiagnoseImpCast(S, E, T, CContext,
9866 diag::warn_impcast_float_integer, PruneWarnings);
9867 }
9868 } else { // IntegerValue.isSigned()
9869 if (!IntegerValue.isMaxSignedValue() &&
9870 !IntegerValue.isMinSignedValue()) {
9871 return DiagnoseImpCast(S, E, T, CContext,
9872 diag::warn_impcast_float_integer, PruneWarnings);
9873 }
9874 }
9875 // Warn on evaluatable floating point expression to integer conversion.
9876 DiagID = diag::warn_impcast_float_to_integer;
9877 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009878
Eli Friedman07185912013-08-29 23:44:43 +00009879 // FIXME: Force the precision of the source value down so we don't print
9880 // digits which are usually useless (we don't really care here if we
9881 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9882 // would automatically print the shortest representation, but it's a bit
9883 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009884 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009885 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9886 precision = (precision * 59 + 195) / 196;
9887 Value.toString(PrettySourceValue, precision);
9888
David Blaikie9b88cc02012-05-15 17:18:27 +00009889 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009890 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009891 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009892 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009893 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009894
Richard Trieube234c32016-04-21 21:04:55 +00009895 if (PruneWarnings) {
9896 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9897 S.PDiag(DiagID)
9898 << E->getType() << T.getUnqualifiedType()
9899 << PrettySourceValue << PrettyTargetValue
9900 << E->getSourceRange() << SourceRange(CContext));
9901 } else {
9902 S.Diag(E->getExprLoc(), DiagID)
9903 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9904 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9905 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009906}
9907
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009908static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9909 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009910 if (!Range.Width) return "0";
9911
9912 llvm::APSInt ValueInRange = Value;
9913 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009914 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009915 return ValueInRange.toString(10);
9916}
9917
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009918static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009919 if (!isa<ImplicitCastExpr>(Ex))
9920 return false;
9921
9922 Expr *InnerE = Ex->IgnoreParenImpCasts();
9923 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9924 const Type *Source =
9925 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9926 if (Target->isDependentType())
9927 return false;
9928
9929 const BuiltinType *FloatCandidateBT =
9930 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9931 const Type *BoolCandidateType = ToBool ? Target : Source;
9932
9933 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9934 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9935}
9936
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009937static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9938 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009939 unsigned NumArgs = TheCall->getNumArgs();
9940 for (unsigned i = 0; i < NumArgs; ++i) {
9941 Expr *CurrA = TheCall->getArg(i);
9942 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9943 continue;
9944
9945 bool IsSwapped = ((i > 0) &&
9946 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9947 IsSwapped |= ((i < (NumArgs - 1)) &&
9948 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9949 if (IsSwapped) {
9950 // Warn on this floating-point to bool conversion.
9951 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9952 CurrA->getType(), CC,
9953 diag::warn_impcast_floating_point_to_bool);
9954 }
9955 }
9956}
9957
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009958static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9959 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009960 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9961 E->getExprLoc()))
9962 return;
9963
Richard Trieu09d6b802016-01-08 23:35:06 +00009964 // Don't warn on functions which have return type nullptr_t.
9965 if (isa<CallExpr>(E))
9966 return;
9967
Richard Trieu5b993502014-10-15 03:42:06 +00009968 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9969 const Expr::NullPointerConstantKind NullKind =
9970 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9971 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9972 return;
9973
9974 // Return if target type is a safe conversion.
9975 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9976 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9977 return;
9978
9979 SourceLocation Loc = E->getSourceRange().getBegin();
9980
Richard Trieu0a5e1662016-02-13 00:58:53 +00009981 // Venture through the macro stacks to get to the source of macro arguments.
9982 // The new location is a better location than the complete location that was
9983 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009984 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9985 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009986
Richard Trieu5b993502014-10-15 03:42:06 +00009987 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009988 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9989 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9990 Loc, S.SourceMgr, S.getLangOpts());
9991 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +00009992 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +00009993 }
9994
9995 // Only warn if the null and context location are in the same macro expansion.
9996 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9997 return;
9998
9999 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010000 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000010001 << FixItHint::CreateReplacement(Loc,
10002 S.getFixItZeroLiteralForType(T, Loc));
10003}
10004
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010005static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10006 ObjCArrayLiteral *ArrayLiteral);
10007
10008static void
10009checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10010 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000010011
10012/// Check a single element within a collection literal against the
10013/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010014static void checkObjCCollectionLiteralElement(Sema &S,
10015 QualType TargetElementType,
10016 Expr *Element,
10017 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010018 // Skip a bitcast to 'id' or qualified 'id'.
10019 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10020 if (ICE->getCastKind() == CK_BitCast &&
10021 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10022 Element = ICE->getSubExpr();
10023 }
10024
10025 QualType ElementType = Element->getType();
10026 ExprResult ElementResult(Element);
10027 if (ElementType->getAs<ObjCObjectPointerType>() &&
10028 S.CheckSingleAssignmentConstraints(TargetElementType,
10029 ElementResult,
10030 false, false)
10031 != Sema::Compatible) {
10032 S.Diag(Element->getLocStart(),
10033 diag::warn_objc_collection_literal_element)
10034 << ElementType << ElementKind << TargetElementType
10035 << Element->getSourceRange();
10036 }
10037
10038 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10039 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10040 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10041 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10042}
10043
10044/// Check an Objective-C array literal being converted to the given
10045/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010046static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10047 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010048 if (!S.NSArrayDecl)
10049 return;
10050
10051 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10052 if (!TargetObjCPtr)
10053 return;
10054
10055 if (TargetObjCPtr->isUnspecialized() ||
10056 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10057 != S.NSArrayDecl->getCanonicalDecl())
10058 return;
10059
10060 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10061 if (TypeArgs.size() != 1)
10062 return;
10063
10064 QualType TargetElementType = TypeArgs[0];
10065 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10066 checkObjCCollectionLiteralElement(S, TargetElementType,
10067 ArrayLiteral->getElement(I),
10068 0);
10069 }
10070}
10071
10072/// Check an Objective-C dictionary literal being converted to the given
10073/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010074static void
10075checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10076 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010077 if (!S.NSDictionaryDecl)
10078 return;
10079
10080 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10081 if (!TargetObjCPtr)
10082 return;
10083
10084 if (TargetObjCPtr->isUnspecialized() ||
10085 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10086 != S.NSDictionaryDecl->getCanonicalDecl())
10087 return;
10088
10089 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10090 if (TypeArgs.size() != 2)
10091 return;
10092
10093 QualType TargetKeyType = TypeArgs[0];
10094 QualType TargetObjectType = TypeArgs[1];
10095 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10096 auto Element = DictionaryLiteral->getKeyValueElement(I);
10097 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10098 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10099 }
10100}
10101
Richard Trieufc404c72016-02-05 23:02:38 +000010102// Helper function to filter out cases for constant width constant conversion.
10103// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010104static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10105 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010106 // If initializing from a constant, and the constant starts with '0',
10107 // then it is a binary, octal, or hexadecimal. Allow these constants
10108 // to fill all the bits, even if there is a sign change.
10109 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10110 const char FirstLiteralCharacter =
10111 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10112 if (FirstLiteralCharacter == '0')
10113 return false;
10114 }
10115
10116 // If the CC location points to a '{', and the type is char, then assume
10117 // assume it is an array initialization.
10118 if (CC.isValid() && T->isCharType()) {
10119 const char FirstContextCharacter =
10120 S.getSourceManager().getCharacterData(CC)[0];
10121 if (FirstContextCharacter == '{')
10122 return false;
10123 }
10124
10125 return true;
10126}
10127
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010128static void
10129CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10130 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010131 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010132
John McCallcc7e5bf2010-05-06 08:58:33 +000010133 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10134 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10135 if (Source == Target) return;
10136 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010137
Chandler Carruthc22845a2011-07-26 05:40:03 +000010138 // If the conversion context location is invalid don't complain. We also
10139 // don't want to emit a warning if the issue occurs from the expansion of
10140 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10141 // delay this check as long as possible. Once we detect we are in that
10142 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010143 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010144 return;
10145
Richard Trieu021baa32011-09-23 20:10:00 +000010146 // Diagnose implicit casts to bool.
10147 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10148 if (isa<StringLiteral>(E))
10149 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010150 // and expressions, for instance, assert(0 && "error here"), are
10151 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010152 return DiagnoseImpCast(S, E, T, CC,
10153 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010154 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10155 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10156 // This covers the literal expressions that evaluate to Objective-C
10157 // objects.
10158 return DiagnoseImpCast(S, E, T, CC,
10159 diag::warn_impcast_objective_c_literal_to_bool);
10160 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010161 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10162 // Warn on pointer to bool conversion that is always true.
10163 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10164 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010165 }
Richard Trieu021baa32011-09-23 20:10:00 +000010166 }
John McCall263a48b2010-01-04 23:31:57 +000010167
Douglas Gregor5054cb02015-07-07 03:58:22 +000010168 // Check implicit casts from Objective-C collection literals to specialized
10169 // collection types, e.g., NSArray<NSString *> *.
10170 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10171 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10172 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10173 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10174
John McCall263a48b2010-01-04 23:31:57 +000010175 // Strip vector types.
10176 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010177 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010178 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010179 return;
John McCallacf0ee52010-10-08 02:01:28 +000010180 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010181 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010182
Chris Lattneree7286f2011-06-14 04:51:15 +000010183 // If the vector cast is cast between two vectors of the same size, it is
10184 // a bitcast, not a conversion.
10185 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10186 return;
John McCall263a48b2010-01-04 23:31:57 +000010187
10188 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10189 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10190 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010191 if (auto VecTy = dyn_cast<VectorType>(Target))
10192 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010193
10194 // Strip complex types.
10195 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010196 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010197 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010198 return;
10199
Tim Northover02416372017-08-08 23:18:05 +000010200 return DiagnoseImpCast(S, E, T, CC,
10201 S.getLangOpts().CPlusPlus
10202 ? diag::err_impcast_complex_scalar
10203 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010204 }
John McCall263a48b2010-01-04 23:31:57 +000010205
10206 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10207 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10208 }
10209
10210 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10211 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10212
10213 // If the source is floating point...
10214 if (SourceBT && SourceBT->isFloatingPoint()) {
10215 // ...and the target is floating point...
10216 if (TargetBT && TargetBT->isFloatingPoint()) {
10217 // ...then warn if we're dropping FP rank.
10218
10219 // Builtin FP kinds are ordered by increasing FP rank.
10220 if (SourceBT->getKind() > TargetBT->getKind()) {
10221 // Don't warn about float constants that are precisely
10222 // representable in the target type.
10223 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010224 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010225 // Value might be a float, a float vector, or a float complex.
10226 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010227 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10228 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010229 return;
10230 }
10231
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010232 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010233 return;
10234
John McCallacf0ee52010-10-08 02:01:28 +000010235 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010236 }
10237 // ... or possibly if we're increasing rank, too
10238 else if (TargetBT->getKind() > SourceBT->getKind()) {
10239 if (S.SourceMgr.isInSystemMacro(CC))
10240 return;
10241
10242 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010243 }
10244 return;
10245 }
10246
Richard Trieube234c32016-04-21 21:04:55 +000010247 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010248 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010249 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010250 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010251
Richard Trieube234c32016-04-21 21:04:55 +000010252 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010253 }
John McCall263a48b2010-01-04 23:31:57 +000010254
Richard Smith54894fd2015-12-30 01:06:52 +000010255 // Detect the case where a call result is converted from floating-point to
10256 // to bool, and the final argument to the call is converted from bool, to
10257 // discover this typo:
10258 //
10259 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10260 //
10261 // FIXME: This is an incredibly special case; is there some more general
10262 // way to detect this class of misplaced-parentheses bug?
10263 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010264 // Check last argument of function call to see if it is an
10265 // implicit cast from a type matching the type the result
10266 // is being cast to.
10267 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010268 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010269 Expr *LastA = CEx->getArg(NumArgs - 1);
10270 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010271 if (isa<ImplicitCastExpr>(LastA) &&
10272 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010273 // Warn on this floating-point to bool conversion
10274 DiagnoseImpCast(S, E, T, CC,
10275 diag::warn_impcast_floating_point_to_bool);
10276 }
10277 }
10278 }
John McCall263a48b2010-01-04 23:31:57 +000010279 return;
10280 }
10281
Richard Trieu5b993502014-10-15 03:42:06 +000010282 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010283
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010284 S.DiscardMisalignedMemberAddress(Target, E);
10285
David Blaikie9366d2b2012-06-19 21:19:06 +000010286 if (!Source->isIntegerType() || !Target->isIntegerType())
10287 return;
10288
David Blaikie7555b6a2012-05-15 16:56:36 +000010289 // TODO: remove this early return once the false positives for constant->bool
10290 // in templates, macros, etc, are reduced or removed.
10291 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10292 return;
10293
John McCallcc7e5bf2010-05-06 08:58:33 +000010294 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010295 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010296
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010297 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010298 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010299 // TODO: this should happen for bitfield stores, too.
10300 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010301 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010302 if (S.SourceMgr.isInSystemMacro(CC))
10303 return;
10304
John McCall18a2c2c2010-11-09 22:22:12 +000010305 std::string PrettySourceValue = Value.toString(10);
10306 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010307
Ted Kremenek33ba9952011-10-22 02:37:33 +000010308 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10309 S.PDiag(diag::warn_impcast_integer_precision_constant)
10310 << PrettySourceValue << PrettyTargetValue
10311 << E->getType() << T << E->getSourceRange()
10312 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010313 return;
10314 }
10315
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010316 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10317 if (S.SourceMgr.isInSystemMacro(CC))
10318 return;
10319
David Blaikie9455da02012-04-12 22:40:54 +000010320 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010321 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10322 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010323 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010324 }
10325
Richard Trieudcb55572016-01-29 23:51:16 +000010326 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10327 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10328 // Warn when doing a signed to signed conversion, warn if the positive
10329 // source value is exactly the width of the target type, which will
10330 // cause a negative value to be stored.
10331
10332 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010333 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10334 !S.SourceMgr.isInSystemMacro(CC)) {
10335 if (isSameWidthConstantConversion(S, E, T, CC)) {
10336 std::string PrettySourceValue = Value.toString(10);
10337 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010338
Richard Trieufc404c72016-02-05 23:02:38 +000010339 S.DiagRuntimeBehavior(
10340 E->getExprLoc(), E,
10341 S.PDiag(diag::warn_impcast_integer_precision_constant)
10342 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10343 << E->getSourceRange() << clang::SourceRange(CC));
10344 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010345 }
10346 }
Richard Trieufc404c72016-02-05 23:02:38 +000010347
Richard Trieudcb55572016-01-29 23:51:16 +000010348 // Fall through for non-constants to give a sign conversion warning.
10349 }
10350
John McCallcc7e5bf2010-05-06 08:58:33 +000010351 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10352 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10353 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010354 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010355 return;
10356
John McCallcc7e5bf2010-05-06 08:58:33 +000010357 unsigned DiagID = diag::warn_impcast_integer_sign;
10358
10359 // Traditionally, gcc has warned about this under -Wsign-compare.
10360 // We also want to warn about it in -Wconversion.
10361 // So if -Wconversion is off, use a completely identical diagnostic
10362 // in the sign-compare group.
10363 // The conditional-checking code will
10364 if (ICContext) {
10365 DiagID = diag::warn_impcast_integer_sign_conditional;
10366 *ICContext = true;
10367 }
10368
John McCallacf0ee52010-10-08 02:01:28 +000010369 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010370 }
10371
Douglas Gregora78f1932011-02-22 02:45:07 +000010372 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010373 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10374 // type, to give us better diagnostics.
10375 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010376 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010377 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10378 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10379 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10380 SourceType = S.Context.getTypeDeclType(Enum);
10381 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10382 }
10383 }
10384
Douglas Gregora78f1932011-02-22 02:45:07 +000010385 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10386 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010387 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10388 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010389 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010390 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010391 return;
10392
Douglas Gregor364f7db2011-03-12 00:14:31 +000010393 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010394 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010395 }
John McCall263a48b2010-01-04 23:31:57 +000010396}
10397
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010398static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10399 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010400
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010401static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10402 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010403 E = E->IgnoreParenImpCasts();
10404
10405 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010406 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010407
John McCallacf0ee52010-10-08 02:01:28 +000010408 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010409 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010410 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010411}
10412
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010413static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10414 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010415 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010416
10417 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010418 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10419 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010420
10421 // If -Wconversion would have warned about either of the candidates
10422 // for a signedness conversion to the context type...
10423 if (!Suspicious) return;
10424
10425 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010426 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010427 return;
10428
John McCallcc7e5bf2010-05-06 08:58:33 +000010429 // ...then check whether it would have warned about either of the
10430 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010431 if (E->getType() == T) return;
10432
10433 Suspicious = false;
10434 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10435 E->getType(), CC, &Suspicious);
10436 if (!Suspicious)
10437 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010438 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010439}
10440
Richard Trieu65724892014-11-15 06:37:39 +000010441/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10442/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010443static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010444 if (S.getLangOpts().Bool)
10445 return;
10446 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10447}
10448
John McCallcc7e5bf2010-05-06 08:58:33 +000010449/// AnalyzeImplicitConversions - Find and report any interesting
10450/// implicit conversions in the given expression. There are a couple
10451/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010452static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10453 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010454 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010455 Expr *E = OrigE->IgnoreParenImpCasts();
10456
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010457 if (E->isTypeDependent() || E->isValueDependent())
10458 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010459
John McCallcc7e5bf2010-05-06 08:58:33 +000010460 // For conditional operators, we analyze the arguments as if they
10461 // were being fed directly into the output.
10462 if (isa<ConditionalOperator>(E)) {
10463 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010464 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010465 return;
10466 }
10467
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010468 // Check implicit argument conversions for function calls.
10469 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10470 CheckImplicitArgumentConversions(S, Call, CC);
10471
John McCallcc7e5bf2010-05-06 08:58:33 +000010472 // Go ahead and check any implicit conversions we might have skipped.
10473 // The non-canonical typecheck is just an optimization;
10474 // CheckImplicitConversion will filter out dead implicit conversions.
10475 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010476 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010477
10478 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010479
10480 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10481 // The bound subexpressions in a PseudoObjectExpr are not reachable
10482 // as transitive children.
10483 // FIXME: Use a more uniform representation for this.
10484 for (auto *SE : POE->semantics())
10485 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10486 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010487 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010488
John McCallcc7e5bf2010-05-06 08:58:33 +000010489 // Skip past explicit casts.
10490 if (isa<ExplicitCastExpr>(E)) {
10491 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010492 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010493 }
10494
John McCalld2a53122010-11-09 23:24:47 +000010495 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10496 // Do a somewhat different check with comparison operators.
10497 if (BO->isComparisonOp())
10498 return AnalyzeComparison(S, BO);
10499
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010500 // And with simple assignments.
10501 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010502 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010503 // And with compound assignments.
10504 if (BO->isAssignmentOp())
10505 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010506 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010507
10508 // These break the otherwise-useful invariant below. Fortunately,
10509 // we don't really need to recurse into them, because any internal
10510 // expressions should have been analyzed already when they were
10511 // built into statements.
10512 if (isa<StmtExpr>(E)) return;
10513
10514 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010515 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010516
10517 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010518 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010519 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010520 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010521 for (Stmt *SubStmt : E->children()) {
10522 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010523 if (!ChildExpr)
10524 continue;
10525
Richard Trieu955231d2014-01-25 01:10:35 +000010526 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010527 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010528 // Ignore checking string literals that are in logical and operators.
10529 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010530 continue;
10531 AnalyzeImplicitConversions(S, ChildExpr, CC);
10532 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010533
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010534 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010535 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10536 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010537 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010538
10539 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10540 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010541 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010542 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010543
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010544 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10545 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010546 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010547}
10548
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010549/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010550static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10551 // Taking into account implicit conversions,
10552 // allow any integer.
10553 if (!E->getType()->isIntegerType()) {
10554 S.Diag(E->getLocStart(),
10555 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10556 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010557 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010558 // Potentially emit standard warnings for implicit conversions if enabled
10559 // using -Wconversion.
10560 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10561 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010562}
10563
Richard Trieuc1888e02014-06-28 23:25:37 +000010564// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10565// Returns true when emitting a warning about taking the address of a reference.
10566static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010567 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010568 E = E->IgnoreParenImpCasts();
10569
10570 const FunctionDecl *FD = nullptr;
10571
10572 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10573 if (!DRE->getDecl()->getType()->isReferenceType())
10574 return false;
10575 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10576 if (!M->getMemberDecl()->getType()->isReferenceType())
10577 return false;
10578 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010579 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010580 return false;
10581 FD = Call->getDirectCallee();
10582 } else {
10583 return false;
10584 }
10585
10586 SemaRef.Diag(E->getExprLoc(), PD);
10587
10588 // If possible, point to location of function.
10589 if (FD) {
10590 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10591 }
10592
10593 return true;
10594}
10595
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010596// Returns true if the SourceLocation is expanded from any macro body.
10597// Returns false if the SourceLocation is invalid, is from not in a macro
10598// expansion, or is from expanded from a top-level macro argument.
10599static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10600 if (Loc.isInvalid())
10601 return false;
10602
10603 while (Loc.isMacroID()) {
10604 if (SM.isMacroBodyExpansion(Loc))
10605 return true;
10606 Loc = SM.getImmediateMacroCallerLoc(Loc);
10607 }
10608
10609 return false;
10610}
10611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010612/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010613/// \param E the expression containing the pointer
10614/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10615/// compared to a null pointer
10616/// \param IsEqual True when the comparison is equal to a null pointer
10617/// \param Range Extra SourceRange to highlight in the diagnostic
10618void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10619 Expr::NullPointerConstantKind NullKind,
10620 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010621 if (!E)
10622 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010623
10624 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010625 if (E->getExprLoc().isMacroID()) {
10626 const SourceManager &SM = getSourceManager();
10627 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10628 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010629 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010630 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010631 E = E->IgnoreImpCasts();
10632
10633 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10634
Richard Trieuf7432752014-06-06 21:39:26 +000010635 if (isa<CXXThisExpr>(E)) {
10636 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10637 : diag::warn_this_bool_conversion;
10638 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10639 return;
10640 }
10641
Richard Trieu3bb8b562014-02-26 02:36:06 +000010642 bool IsAddressOf = false;
10643
10644 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10645 if (UO->getOpcode() != UO_AddrOf)
10646 return;
10647 IsAddressOf = true;
10648 E = UO->getSubExpr();
10649 }
10650
Richard Trieuc1888e02014-06-28 23:25:37 +000010651 if (IsAddressOf) {
10652 unsigned DiagID = IsCompare
10653 ? diag::warn_address_of_reference_null_compare
10654 : diag::warn_address_of_reference_bool_conversion;
10655 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10656 << IsEqual;
10657 if (CheckForReference(*this, E, PD)) {
10658 return;
10659 }
10660 }
10661
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010662 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10663 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010664 std::string Str;
10665 llvm::raw_string_ostream S(Str);
10666 E->printPretty(S, nullptr, getPrintingPolicy());
10667 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10668 : diag::warn_cast_nonnull_to_bool;
10669 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10670 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010671 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010672 };
10673
10674 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10675 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10676 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010677 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10678 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010679 return;
10680 }
10681 }
10682 }
10683
Richard Trieu3bb8b562014-02-26 02:36:06 +000010684 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010685 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010686 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10687 D = R->getDecl();
10688 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10689 D = M->getMemberDecl();
10690 }
10691
10692 // Weak Decls can be null.
10693 if (!D || D->isWeak())
10694 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010695
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010696 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010697 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10698 if (getCurFunction() &&
10699 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010700 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10701 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010702 return;
10703 }
10704
10705 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010706 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010707 assert(ParamIter != FD->param_end());
10708 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10709
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010710 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10711 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010712 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010713 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010714 }
George Burgess IV850269a2015-12-08 22:02:00 +000010715
Joel E. Denny81508102018-03-13 14:51:22 +000010716 for (const ParamIdx &ArgNo : NonNull->args()) {
10717 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010718 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010719 return;
10720 }
George Burgess IV850269a2015-12-08 22:02:00 +000010721 }
10722 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010723 }
10724 }
George Burgess IV850269a2015-12-08 22:02:00 +000010725 }
10726
Richard Trieu3bb8b562014-02-26 02:36:06 +000010727 QualType T = D->getType();
10728 const bool IsArray = T->isArrayType();
10729 const bool IsFunction = T->isFunctionType();
10730
Richard Trieuc1888e02014-06-28 23:25:37 +000010731 // Address of function is used to silence the function warning.
10732 if (IsAddressOf && IsFunction) {
10733 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010734 }
10735
10736 // Found nothing.
10737 if (!IsAddressOf && !IsFunction && !IsArray)
10738 return;
10739
10740 // Pretty print the expression for the diagnostic.
10741 std::string Str;
10742 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010743 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010744
10745 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10746 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010747 enum {
10748 AddressOf,
10749 FunctionPointer,
10750 ArrayPointer
10751 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010752 if (IsAddressOf)
10753 DiagType = AddressOf;
10754 else if (IsFunction)
10755 DiagType = FunctionPointer;
10756 else if (IsArray)
10757 DiagType = ArrayPointer;
10758 else
10759 llvm_unreachable("Could not determine diagnostic.");
10760 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10761 << Range << IsEqual;
10762
10763 if (!IsFunction)
10764 return;
10765
10766 // Suggest '&' to silence the function warning.
10767 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10768 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10769
10770 // Check to see if '()' fixit should be emitted.
10771 QualType ReturnType;
10772 UnresolvedSet<4> NonTemplateOverloads;
10773 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10774 if (ReturnType.isNull())
10775 return;
10776
10777 if (IsCompare) {
10778 // There are two cases here. If there is null constant, the only suggest
10779 // for a pointer return type. If the null is 0, then suggest if the return
10780 // type is a pointer or an integer type.
10781 if (!ReturnType->isPointerType()) {
10782 if (NullKind == Expr::NPCK_ZeroExpression ||
10783 NullKind == Expr::NPCK_ZeroLiteral) {
10784 if (!ReturnType->isIntegerType())
10785 return;
10786 } else {
10787 return;
10788 }
10789 }
10790 } else { // !IsCompare
10791 // For function to bool, only suggest if the function pointer has bool
10792 // return type.
10793 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10794 return;
10795 }
10796 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010797 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010798}
10799
John McCallcc7e5bf2010-05-06 08:58:33 +000010800/// Diagnoses "dangerous" implicit conversions within the given
10801/// expression (which is a full expression). Implements -Wconversion
10802/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010803///
10804/// \param CC the "context" location of the implicit conversion, i.e.
10805/// the most location of the syntactic entity requiring the implicit
10806/// conversion
10807void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010808 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010809 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010810 return;
10811
10812 // Don't diagnose for value- or type-dependent expressions.
10813 if (E->isTypeDependent() || E->isValueDependent())
10814 return;
10815
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010816 // Check for array bounds violations in cases where the check isn't triggered
10817 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10818 // ArraySubscriptExpr is on the RHS of a variable initialization.
10819 CheckArrayAccess(E);
10820
John McCallacf0ee52010-10-08 02:01:28 +000010821 // This is not the right CC for (e.g.) a variable initialization.
10822 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010823}
10824
Richard Trieu65724892014-11-15 06:37:39 +000010825/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10826/// Input argument E is a logical expression.
10827void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10828 ::CheckBoolLikeConversion(*this, E, CC);
10829}
10830
Richard Smith9f7df0c2017-06-26 23:19:32 +000010831/// Diagnose when expression is an integer constant expression and its evaluation
10832/// results in integer overflow
10833void Sema::CheckForIntOverflow (Expr *E) {
10834 // Use a work list to deal with nested struct initializers.
10835 SmallVector<Expr *, 2> Exprs(1, E);
10836
10837 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010838 Expr *OriginalE = Exprs.pop_back_val();
10839 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010840
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010841 if (isa<BinaryOperator>(E)) {
10842 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010843 continue;
10844 }
10845
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010846 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010847 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010848 else if (isa<ObjCBoxedExpr>(OriginalE))
10849 E->EvaluateForOverflow(Context);
10850 else if (auto Call = dyn_cast<CallExpr>(E))
10851 Exprs.append(Call->arg_begin(), Call->arg_end());
10852 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10853 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010854 } while (!Exprs.empty());
10855}
10856
Richard Smithc406cb72013-01-17 01:17:56 +000010857namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010859/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010860/// same object.
10861class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010862 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010863
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010864 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010865 /// unsequenced if one is an ancestor or a descendent of the other. When we
10866 /// finish processing an expression with sequencing, such as a comma
10867 /// expression, we fold its tree nodes into its parent, since they are
10868 /// unsequenced with respect to nodes we will visit later.
10869 class SequenceTree {
10870 struct Value {
10871 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10872 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010873 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010874 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010875 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010876
10877 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010878 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010879 /// to some other region.
10880 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010881 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010882
10883 unsigned Index = 0;
10884
10885 explicit Seq(unsigned N) : Index(N) {}
10886
Richard Smithc406cb72013-01-17 01:17:56 +000010887 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010888 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010889 };
10890
10891 SequenceTree() { Values.push_back(Value(0)); }
10892 Seq root() const { return Seq(0); }
10893
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010894 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010895 /// subset of \p Parent. This sequence of operations is sequenced with
10896 /// respect to other children of \p Parent.
10897 Seq allocate(Seq Parent) {
10898 Values.push_back(Value(Parent.Index));
10899 return Seq(Values.size() - 1);
10900 }
10901
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010902 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010903 void merge(Seq S) {
10904 Values[S.Index].Merged = true;
10905 }
10906
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010907 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010908 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10909 /// should have been merged into its parent as appropriate.
10910 bool isUnsequenced(Seq Cur, Seq Old) {
10911 unsigned C = representative(Cur.Index);
10912 unsigned Target = representative(Old.Index);
10913 while (C >= Target) {
10914 if (C == Target)
10915 return true;
10916 C = Values[C].Parent;
10917 }
10918 return false;
10919 }
10920
10921 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010922 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010923 unsigned representative(unsigned K) {
10924 if (Values[K].Merged)
10925 // Perform path compression as we go.
10926 return Values[K].Parent = representative(Values[K].Parent);
10927 return K;
10928 }
10929 };
10930
10931 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010932 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010933
10934 /// Different flavors of object usage which we track. We only track the
10935 /// least-sequenced usage of each kind.
10936 enum UsageKind {
10937 /// A read of an object. Multiple unsequenced reads are OK.
10938 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010939
Richard Smithc406cb72013-01-17 01:17:56 +000010940 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010941 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010942 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010943
Richard Smithc406cb72013-01-17 01:17:56 +000010944 /// A modification of an object which is not sequenced before the value
10945 /// computation of the expression, such as n++.
10946 UK_ModAsSideEffect,
10947
10948 UK_Count = UK_ModAsSideEffect + 1
10949 };
10950
10951 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010952 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010953 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010954
10955 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010956 };
10957
10958 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010959 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010960
Richard Smithc406cb72013-01-17 01:17:56 +000010961 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010962 bool Diagnosed = false;
10963
10964 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010965 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010966 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010967
10968 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010969
Richard Smithc406cb72013-01-17 01:17:56 +000010970 /// Sequenced regions within the expression.
10971 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010972
Richard Smithc406cb72013-01-17 01:17:56 +000010973 /// Declaration modifications and references which we have seen.
10974 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010975
Richard Smithc406cb72013-01-17 01:17:56 +000010976 /// The region we are currently within.
10977 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010978
Richard Smithc406cb72013-01-17 01:17:56 +000010979 /// Filled in with declarations which were modified as a side-effect
10980 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010981 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10982
Richard Smithd33f5202013-01-17 23:18:09 +000010983 /// Expressions to check later. We defer checking these to reduce
10984 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010985 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010986
10987 /// RAII object wrapping the visitation of a sequenced subexpression of an
10988 /// expression. At the end of this process, the side-effects of the evaluation
10989 /// become sequenced with respect to the value computation of the result, so
10990 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10991 /// UK_ModAsValue.
10992 struct SequencedSubexpression {
10993 SequencedSubexpression(SequenceChecker &Self)
10994 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10995 Self.ModAsSideEffect = &ModAsSideEffect;
10996 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010997
Richard Smithc406cb72013-01-17 01:17:56 +000010998 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010999 for (auto &M : llvm::reverse(ModAsSideEffect)) {
11000 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000011001 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000011002 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11003 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000011004 }
11005 Self.ModAsSideEffect = OldModAsSideEffect;
11006 }
11007
11008 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011009 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011010 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000011011 };
11012
Richard Smith40238f02013-06-20 22:21:56 +000011013 /// RAII object wrapping the visitation of a subexpression which we might
11014 /// choose to evaluate as a constant. If any subexpression is evaluated and
11015 /// found to be non-constant, this allows us to suppress the evaluation of
11016 /// the outer expression.
11017 class EvaluationTracker {
11018 public:
11019 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011020 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000011021 Self.EvalTracker = this;
11022 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011023
Richard Smith40238f02013-06-20 22:21:56 +000011024 ~EvaluationTracker() {
11025 Self.EvalTracker = Prev;
11026 if (Prev)
11027 Prev->EvalOK &= EvalOK;
11028 }
11029
11030 bool evaluate(const Expr *E, bool &Result) {
11031 if (!EvalOK || E->isValueDependent())
11032 return false;
11033 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11034 return EvalOK;
11035 }
11036
11037 private:
11038 SequenceChecker &Self;
11039 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011040 bool EvalOK = true;
11041 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000011042
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011043 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000011044 /// if any.
11045 Object getObject(Expr *E, bool Mod) const {
11046 E = E->IgnoreParenCasts();
11047 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11048 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11049 return getObject(UO->getSubExpr(), Mod);
11050 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11051 if (BO->getOpcode() == BO_Comma)
11052 return getObject(BO->getRHS(), Mod);
11053 if (Mod && BO->isAssignmentOp())
11054 return getObject(BO->getLHS(), Mod);
11055 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11056 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11057 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11058 return ME->getMemberDecl();
11059 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11060 // FIXME: If this is a reference, map through to its value.
11061 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000011062 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011063 }
11064
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011065 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011066 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11067 Usage &U = UI.Uses[UK];
11068 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11069 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11070 ModAsSideEffect->push_back(std::make_pair(O, U));
11071 U.Use = Ref;
11072 U.Seq = Region;
11073 }
11074 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011076 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011077 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11078 bool IsModMod) {
11079 if (UI.Diagnosed)
11080 return;
11081
11082 const Usage &U = UI.Uses[OtherKind];
11083 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11084 return;
11085
11086 Expr *Mod = U.Use;
11087 Expr *ModOrUse = Ref;
11088 if (OtherKind == UK_Use)
11089 std::swap(Mod, ModOrUse);
11090
11091 SemaRef.Diag(Mod->getExprLoc(),
11092 IsModMod ? diag::warn_unsequenced_mod_mod
11093 : diag::warn_unsequenced_mod_use)
11094 << O << SourceRange(ModOrUse->getExprLoc());
11095 UI.Diagnosed = true;
11096 }
11097
11098 void notePreUse(Object O, Expr *Use) {
11099 UsageInfo &U = UsageMap[O];
11100 // Uses conflict with other modifications.
11101 checkUsage(O, U, Use, UK_ModAsValue, false);
11102 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011103
Richard Smithc406cb72013-01-17 01:17:56 +000011104 void notePostUse(Object O, Expr *Use) {
11105 UsageInfo &U = UsageMap[O];
11106 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11107 addUsage(U, O, Use, UK_Use);
11108 }
11109
11110 void notePreMod(Object O, Expr *Mod) {
11111 UsageInfo &U = UsageMap[O];
11112 // Modifications conflict with other modifications and with uses.
11113 checkUsage(O, U, Mod, UK_ModAsValue, true);
11114 checkUsage(O, U, Mod, UK_Use, false);
11115 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011116
Richard Smithc406cb72013-01-17 01:17:56 +000011117 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11118 UsageInfo &U = UsageMap[O];
11119 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11120 addUsage(U, O, Use, UK);
11121 }
11122
11123public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011124 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011125 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011126 Visit(E);
11127 }
11128
11129 void VisitStmt(Stmt *S) {
11130 // Skip all statements which aren't expressions for now.
11131 }
11132
11133 void VisitExpr(Expr *E) {
11134 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011135 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011136 }
11137
11138 void VisitCastExpr(CastExpr *E) {
11139 Object O = Object();
11140 if (E->getCastKind() == CK_LValueToRValue)
11141 O = getObject(E->getSubExpr(), false);
11142
11143 if (O)
11144 notePreUse(O, E);
11145 VisitExpr(E);
11146 if (O)
11147 notePostUse(O, E);
11148 }
11149
11150 void VisitBinComma(BinaryOperator *BO) {
11151 // C++11 [expr.comma]p1:
11152 // Every value computation and side effect associated with the left
11153 // expression is sequenced before every value computation and side
11154 // effect associated with the right expression.
11155 SequenceTree::Seq LHS = Tree.allocate(Region);
11156 SequenceTree::Seq RHS = Tree.allocate(Region);
11157 SequenceTree::Seq OldRegion = Region;
11158
11159 {
11160 SequencedSubexpression SeqLHS(*this);
11161 Region = LHS;
11162 Visit(BO->getLHS());
11163 }
11164
11165 Region = RHS;
11166 Visit(BO->getRHS());
11167
11168 Region = OldRegion;
11169
11170 // Forget that LHS and RHS are sequenced. They are both unsequenced
11171 // with respect to other stuff.
11172 Tree.merge(LHS);
11173 Tree.merge(RHS);
11174 }
11175
11176 void VisitBinAssign(BinaryOperator *BO) {
11177 // The modification is sequenced after the value computation of the LHS
11178 // and RHS, so check it before inspecting the operands and update the
11179 // map afterwards.
11180 Object O = getObject(BO->getLHS(), true);
11181 if (!O)
11182 return VisitExpr(BO);
11183
11184 notePreMod(O, BO);
11185
11186 // C++11 [expr.ass]p7:
11187 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11188 // only once.
11189 //
11190 // Therefore, for a compound assignment operator, O is considered used
11191 // everywhere except within the evaluation of E1 itself.
11192 if (isa<CompoundAssignOperator>(BO))
11193 notePreUse(O, BO);
11194
11195 Visit(BO->getLHS());
11196
11197 if (isa<CompoundAssignOperator>(BO))
11198 notePostUse(O, BO);
11199
11200 Visit(BO->getRHS());
11201
Richard Smith83e37bee2013-06-26 23:16:51 +000011202 // C++11 [expr.ass]p1:
11203 // the assignment is sequenced [...] before the value computation of the
11204 // assignment expression.
11205 // C11 6.5.16/3 has no such rule.
11206 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11207 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011208 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011209
Richard Smithc406cb72013-01-17 01:17:56 +000011210 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11211 VisitBinAssign(CAO);
11212 }
11213
11214 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11215 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11216 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11217 Object O = getObject(UO->getSubExpr(), true);
11218 if (!O)
11219 return VisitExpr(UO);
11220
11221 notePreMod(O, UO);
11222 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011223 // C++11 [expr.pre.incr]p1:
11224 // the expression ++x is equivalent to x+=1
11225 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11226 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011227 }
11228
11229 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11230 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11231 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11232 Object O = getObject(UO->getSubExpr(), true);
11233 if (!O)
11234 return VisitExpr(UO);
11235
11236 notePreMod(O, UO);
11237 Visit(UO->getSubExpr());
11238 notePostMod(O, UO, UK_ModAsSideEffect);
11239 }
11240
11241 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11242 void VisitBinLOr(BinaryOperator *BO) {
11243 // The side-effects of the LHS of an '&&' are sequenced before the
11244 // value computation of the RHS, and hence before the value computation
11245 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11246 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011247 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011248 {
11249 SequencedSubexpression Sequenced(*this);
11250 Visit(BO->getLHS());
11251 }
11252
11253 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011254 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011255 if (!Result)
11256 Visit(BO->getRHS());
11257 } else {
11258 // Check for unsequenced operations in the RHS, treating it as an
11259 // entirely separate evaluation.
11260 //
11261 // FIXME: If there are operations in the RHS which are unsequenced
11262 // with respect to operations outside the RHS, and those operations
11263 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011264 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011265 }
Richard Smithc406cb72013-01-17 01:17:56 +000011266 }
11267 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011268 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011269 {
11270 SequencedSubexpression Sequenced(*this);
11271 Visit(BO->getLHS());
11272 }
11273
11274 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011275 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011276 if (Result)
11277 Visit(BO->getRHS());
11278 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011279 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011280 }
Richard Smithc406cb72013-01-17 01:17:56 +000011281 }
11282
11283 // Only visit the condition, unless we can be sure which subexpression will
11284 // be chosen.
11285 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011286 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011287 {
11288 SequencedSubexpression Sequenced(*this);
11289 Visit(CO->getCond());
11290 }
Richard Smithc406cb72013-01-17 01:17:56 +000011291
11292 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011293 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011294 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011295 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011296 WorkList.push_back(CO->getTrueExpr());
11297 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011298 }
Richard Smithc406cb72013-01-17 01:17:56 +000011299 }
11300
Richard Smithe3dbfe02013-06-30 10:40:20 +000011301 void VisitCallExpr(CallExpr *CE) {
11302 // C++11 [intro.execution]p15:
11303 // When calling a function [...], every value computation and side effect
11304 // associated with any argument expression, or with the postfix expression
11305 // designating the called function, is sequenced before execution of every
11306 // expression or statement in the body of the function [and thus before
11307 // the value computation of its result].
11308 SequencedSubexpression Sequenced(*this);
11309 Base::VisitCallExpr(CE);
11310
11311 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11312 }
11313
Richard Smithc406cb72013-01-17 01:17:56 +000011314 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011315 // This is a call, so all subexpressions are sequenced before the result.
11316 SequencedSubexpression Sequenced(*this);
11317
Richard Smithc406cb72013-01-17 01:17:56 +000011318 if (!CCE->isListInitialization())
11319 return VisitExpr(CCE);
11320
11321 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011322 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011323 SequenceTree::Seq Parent = Region;
11324 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11325 E = CCE->arg_end();
11326 I != E; ++I) {
11327 Region = Tree.allocate(Parent);
11328 Elts.push_back(Region);
11329 Visit(*I);
11330 }
11331
11332 // Forget that the initializers are sequenced.
11333 Region = Parent;
11334 for (unsigned I = 0; I < Elts.size(); ++I)
11335 Tree.merge(Elts[I]);
11336 }
11337
11338 void VisitInitListExpr(InitListExpr *ILE) {
11339 if (!SemaRef.getLangOpts().CPlusPlus11)
11340 return VisitExpr(ILE);
11341
11342 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011343 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011344 SequenceTree::Seq Parent = Region;
11345 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11346 Expr *E = ILE->getInit(I);
11347 if (!E) continue;
11348 Region = Tree.allocate(Parent);
11349 Elts.push_back(Region);
11350 Visit(E);
11351 }
11352
11353 // Forget that the initializers are sequenced.
11354 Region = Parent;
11355 for (unsigned I = 0; I < Elts.size(); ++I)
11356 Tree.merge(Elts[I]);
11357 }
11358};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011359
11360} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011361
11362void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011363 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011364 WorkList.push_back(E);
11365 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011366 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011367 SequenceChecker(*this, Item, WorkList);
11368 }
Richard Smithc406cb72013-01-17 01:17:56 +000011369}
11370
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011371void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11372 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011373 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011374 if (!E->isInstantiationDependent())
11375 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011376 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011377 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011378 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011379}
11380
John McCall1f425642010-11-11 03:21:53 +000011381void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11382 FieldDecl *BitField,
11383 Expr *Init) {
11384 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11385}
11386
David Majnemer61a5bbf2015-04-07 22:08:51 +000011387static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11388 SourceLocation Loc) {
11389 if (!PType->isVariablyModifiedType())
11390 return;
11391 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11392 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11393 return;
11394 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011395 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11396 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11397 return;
11398 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011399 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11400 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11401 return;
11402 }
11403
11404 const ArrayType *AT = S.Context.getAsArrayType(PType);
11405 if (!AT)
11406 return;
11407
11408 if (AT->getSizeModifier() != ArrayType::Star) {
11409 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11410 return;
11411 }
11412
11413 S.Diag(Loc, diag::err_array_star_in_function_definition);
11414}
11415
Mike Stump0c2ec772010-01-21 03:59:47 +000011416/// CheckParmsForFunctionDef - Check that the parameters of the given
11417/// function are appropriate for the definition of a function. This
11418/// takes care of any checks that cannot be performed on the
11419/// declaration itself, e.g., that the types of each of the function
11420/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011421bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011422 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011423 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011424 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011425 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11426 // function declarator that is part of a function definition of
11427 // that function shall not have incomplete type.
11428 //
11429 // This is also C++ [dcl.fct]p6.
11430 if (!Param->isInvalidDecl() &&
11431 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011432 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011433 Param->setInvalidDecl();
11434 HasInvalidParm = true;
11435 }
11436
11437 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11438 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011439 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011440 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011441 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011442 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011443 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011444
11445 // C99 6.7.5.3p12:
11446 // If the function declarator is not part of a definition of that
11447 // function, parameters may have incomplete type and may use the [*]
11448 // notation in their sequences of declarator specifiers to specify
11449 // variable length array types.
11450 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011451 // FIXME: This diagnostic should point the '[*]' if source-location
11452 // information is added for it.
11453 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011454
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011455 // If the parameter is a c++ class type and it has to be destructed in the
11456 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011457 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011458 if (!Param->isInvalidDecl()) {
11459 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11460 if (!ClassDecl->isInvalidDecl() &&
11461 !ClassDecl->hasIrrelevantDestructor() &&
11462 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011463 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011464 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11465 MarkFunctionReferenced(Param->getLocation(), Destructor);
11466 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011467 }
11468 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011469 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011470
11471 // Parameters with the pass_object_size attribute only need to be marked
11472 // constant at function definitions. Because we lack information about
11473 // whether we're on a declaration or definition when we're instantiating the
11474 // attribute, we need to check for constness here.
11475 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11476 if (!Param->getType().isConstQualified())
11477 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11478 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011479 }
11480
11481 return HasInvalidParm;
11482}
John McCall2b5c1b22010-08-12 21:44:57 +000011483
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011484/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11485/// or MemberExpr.
11486static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11487 ASTContext &Context) {
11488 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11489 return Context.getDeclAlign(DRE->getDecl());
11490
11491 if (const auto *ME = dyn_cast<MemberExpr>(E))
11492 return Context.getDeclAlign(ME->getMemberDecl());
11493
11494 return TypeAlign;
11495}
11496
John McCall2b5c1b22010-08-12 21:44:57 +000011497/// CheckCastAlign - Implements -Wcast-align, which warns when a
11498/// pointer cast increases the alignment requirements.
11499void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11500 // This is actually a lot of work to potentially be doing on every
11501 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011502 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011503 return;
11504
11505 // Ignore dependent types.
11506 if (T->isDependentType() || Op->getType()->isDependentType())
11507 return;
11508
11509 // Require that the destination be a pointer type.
11510 const PointerType *DestPtr = T->getAs<PointerType>();
11511 if (!DestPtr) return;
11512
11513 // If the destination has alignment 1, we're done.
11514 QualType DestPointee = DestPtr->getPointeeType();
11515 if (DestPointee->isIncompleteType()) return;
11516 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11517 if (DestAlign.isOne()) return;
11518
11519 // Require that the source be a pointer type.
11520 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11521 if (!SrcPtr) return;
11522 QualType SrcPointee = SrcPtr->getPointeeType();
11523
11524 // Whitelist casts from cv void*. We already implicitly
11525 // whitelisted casts to cv void*, since they have alignment 1.
11526 // Also whitelist casts involving incomplete types, which implicitly
11527 // includes 'void'.
11528 if (SrcPointee->isIncompleteType()) return;
11529
11530 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011531
11532 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11533 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11534 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11535 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11536 if (UO->getOpcode() == UO_AddrOf)
11537 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11538 }
11539
John McCall2b5c1b22010-08-12 21:44:57 +000011540 if (SrcAlign >= DestAlign) return;
11541
11542 Diag(TRange.getBegin(), diag::warn_cast_align)
11543 << Op->getType() << T
11544 << static_cast<unsigned>(SrcAlign.getQuantity())
11545 << static_cast<unsigned>(DestAlign.getQuantity())
11546 << TRange << Op->getSourceRange();
11547}
11548
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011549/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011550/// array member of a struct.
11551///
11552/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11553/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011554static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011555 const NamedDecl *ND) {
11556 if (Size != 1 || !ND) return false;
11557
11558 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11559 if (!FD) return false;
11560
11561 // Don't consider sizes resulting from macro expansions or template argument
11562 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011563
11564 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011565 while (TInfo) {
11566 TypeLoc TL = TInfo->getTypeLoc();
11567 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011568 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11569 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011570 TInfo = TDL->getTypeSourceInfo();
11571 continue;
11572 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011573 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11574 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011575 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11576 return false;
11577 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011578 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011579 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011580
11581 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011582 if (!RD) return false;
11583 if (RD->isUnion()) return false;
11584 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11585 if (!CRD->isStandardLayout()) return false;
11586 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011587
Benjamin Kramer8c543672011-08-06 03:04:42 +000011588 // See if this is the last field decl in the record.
11589 const Decl *D = FD;
11590 while ((D = D->getNextDeclInContext()))
11591 if (isa<FieldDecl>(D))
11592 return false;
11593 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011594}
11595
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011596void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011597 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011598 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011599 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011600 if (IndexExpr->isValueDependent())
11601 return;
11602
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011603 const Type *EffectiveType =
11604 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011605 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011606 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011607 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011608 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011609 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011610
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011611 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011612 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011613 return;
Richard Smith13f67182011-12-16 19:31:14 +000011614 if (IndexNegated)
11615 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011616
Craig Topperc3ec1492014-05-26 06:22:03 +000011617 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011618 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011619 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011620 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011621 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011622
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011623 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011624 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011625 if (!size.isStrictlyPositive())
11626 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011627
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011628 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011629 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011630 // Make sure we're comparing apples to apples when comparing index to size
11631 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11632 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011633 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011634 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011635 if (ptrarith_typesize != array_typesize) {
11636 // There's a cast to a different size type involved
11637 uint64_t ratio = array_typesize / ptrarith_typesize;
11638 // TODO: Be smarter about handling cases where array_typesize is not a
11639 // multiple of ptrarith_typesize
11640 if (ptrarith_typesize * ratio == array_typesize)
11641 size *= llvm::APInt(size.getBitWidth(), ratio);
11642 }
11643 }
11644
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011645 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011646 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011647 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011648 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011649
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011650 // For array subscripting the index must be less than size, but for pointer
11651 // arithmetic also allow the index (offset) to be equal to size since
11652 // computing the next address after the end of the array is legal and
11653 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011654 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011655 return;
11656
11657 // Also don't warn for arrays of size 1 which are members of some
11658 // structure. These are often used to approximate flexible arrays in C89
11659 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011660 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011661 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011662
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011663 // Suppress the warning if the subscript expression (as identified by the
11664 // ']' location) and the index expression are both from macro expansions
11665 // within a system header.
11666 if (ASE) {
11667 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11668 ASE->getRBracketLoc());
11669 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11670 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11671 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011672 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011673 return;
11674 }
11675 }
11676
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011677 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011678 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011679 DiagID = diag::warn_array_index_exceeds_bounds;
11680
11681 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11682 PDiag(DiagID) << index.toString(10, true)
11683 << size.toString(10, true)
11684 << (unsigned)size.getLimitedValue(~0U)
11685 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011686 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011687 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011688 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011689 DiagID = diag::warn_ptr_arith_precedes_bounds;
11690 if (index.isNegative()) index = -index;
11691 }
11692
11693 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11694 PDiag(DiagID) << index.toString(10, true)
11695 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011696 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011697
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011698 if (!ND) {
11699 // Try harder to find a NamedDecl to point at in the note.
11700 while (const ArraySubscriptExpr *ASE =
11701 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11702 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11703 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011704 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011705 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011706 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011707 }
11708
Chandler Carruth1af88f12011-02-17 21:10:52 +000011709 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011710 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11711 PDiag(diag::note_array_index_out_of_bounds)
11712 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011713}
11714
Ted Kremenekdf26df72011-03-01 18:41:00 +000011715void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011716 int AllowOnePastEnd = 0;
11717 while (expr) {
11718 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011719 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011720 case Stmt::ArraySubscriptExprClass: {
11721 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011722 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011723 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011724 expr = ASE->getBase();
11725 break;
11726 }
11727 case Stmt::MemberExprClass: {
11728 expr = cast<MemberExpr>(expr)->getBase();
11729 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011730 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011731 case Stmt::OMPArraySectionExprClass: {
11732 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11733 if (ASE->getLowerBound())
11734 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11735 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11736 return;
11737 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011738 case Stmt::UnaryOperatorClass: {
11739 // Only unwrap the * and & unary operators
11740 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11741 expr = UO->getSubExpr();
11742 switch (UO->getOpcode()) {
11743 case UO_AddrOf:
11744 AllowOnePastEnd++;
11745 break;
11746 case UO_Deref:
11747 AllowOnePastEnd--;
11748 break;
11749 default:
11750 return;
11751 }
11752 break;
11753 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011754 case Stmt::ConditionalOperatorClass: {
11755 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11756 if (const Expr *lhs = cond->getLHS())
11757 CheckArrayAccess(lhs);
11758 if (const Expr *rhs = cond->getRHS())
11759 CheckArrayAccess(rhs);
11760 return;
11761 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011762 case Stmt::CXXOperatorCallExprClass: {
11763 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11764 for (const auto *Arg : OCE->arguments())
11765 CheckArrayAccess(Arg);
11766 return;
11767 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011768 default:
11769 return;
11770 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011771 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011772}
John McCall31168b02011-06-15 23:02:42 +000011773
11774//===--- CHECK: Objective-C retain cycles ----------------------------------//
11775
11776namespace {
John McCall31168b02011-06-15 23:02:42 +000011777
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011778struct RetainCycleOwner {
11779 VarDecl *Variable = nullptr;
11780 SourceRange Range;
11781 SourceLocation Loc;
11782 bool Indirect = false;
11783
11784 RetainCycleOwner() = default;
11785
11786 void setLocsFrom(Expr *e) {
11787 Loc = e->getExprLoc();
11788 Range = e->getSourceRange();
11789 }
11790};
11791
11792} // namespace
John McCall31168b02011-06-15 23:02:42 +000011793
11794/// Consider whether capturing the given variable can possibly lead to
11795/// a retain cycle.
11796static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011797 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011798 // lifetime. In MRR, it's captured strongly if the variable is
11799 // __block and has an appropriate type.
11800 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11801 return false;
11802
11803 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011804 if (ref)
11805 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011806 return true;
11807}
11808
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011809static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011810 while (true) {
11811 e = e->IgnoreParens();
11812 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11813 switch (cast->getCastKind()) {
11814 case CK_BitCast:
11815 case CK_LValueBitCast:
11816 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011817 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011818 e = cast->getSubExpr();
11819 continue;
11820
John McCall31168b02011-06-15 23:02:42 +000011821 default:
11822 return false;
11823 }
11824 }
11825
11826 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11827 ObjCIvarDecl *ivar = ref->getDecl();
11828 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11829 return false;
11830
11831 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011832 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011833 return false;
11834
11835 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11836 owner.Indirect = true;
11837 return true;
11838 }
11839
11840 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11841 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11842 if (!var) return false;
11843 return considerVariable(var, ref, owner);
11844 }
11845
John McCall31168b02011-06-15 23:02:42 +000011846 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11847 if (member->isArrow()) return false;
11848
11849 // Don't count this as an indirect ownership.
11850 e = member->getBase();
11851 continue;
11852 }
11853
John McCallfe96e0b2011-11-06 09:01:30 +000011854 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11855 // Only pay attention to pseudo-objects on property references.
11856 ObjCPropertyRefExpr *pre
11857 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11858 ->IgnoreParens());
11859 if (!pre) return false;
11860 if (pre->isImplicitProperty()) return false;
11861 ObjCPropertyDecl *property = pre->getExplicitProperty();
11862 if (!property->isRetaining() &&
11863 !(property->getPropertyIvarDecl() &&
11864 property->getPropertyIvarDecl()->getType()
11865 .getObjCLifetime() == Qualifiers::OCL_Strong))
11866 return false;
11867
11868 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011869 if (pre->isSuperReceiver()) {
11870 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11871 if (!owner.Variable)
11872 return false;
11873 owner.Loc = pre->getLocation();
11874 owner.Range = pre->getSourceRange();
11875 return true;
11876 }
John McCallfe96e0b2011-11-06 09:01:30 +000011877 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11878 ->getSourceExpr());
11879 continue;
11880 }
11881
John McCall31168b02011-06-15 23:02:42 +000011882 // Array ivars?
11883
11884 return false;
11885 }
11886}
11887
11888namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011889
John McCall31168b02011-06-15 23:02:42 +000011890 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011891 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011892 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011893 Expr *Capturer = nullptr;
11894 bool VarWillBeReased = false;
11895
11896 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11897 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11898 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011899
11900 void VisitDeclRefExpr(DeclRefExpr *ref) {
11901 if (ref->getDecl() == Variable && !Capturer)
11902 Capturer = ref;
11903 }
11904
John McCall31168b02011-06-15 23:02:42 +000011905 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11906 if (Capturer) return;
11907 Visit(ref->getBase());
11908 if (Capturer && ref->isFreeIvar())
11909 Capturer = ref;
11910 }
11911
11912 void VisitBlockExpr(BlockExpr *block) {
11913 // Look inside nested blocks
11914 if (block->getBlockDecl()->capturesVariable(Variable))
11915 Visit(block->getBlockDecl()->getBody());
11916 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011917
11918 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11919 if (Capturer) return;
11920 if (OVE->getSourceExpr())
11921 Visit(OVE->getSourceExpr());
11922 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011923
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011924 void VisitBinaryOperator(BinaryOperator *BinOp) {
11925 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11926 return;
11927 Expr *LHS = BinOp->getLHS();
11928 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11929 if (DRE->getDecl() != Variable)
11930 return;
11931 if (Expr *RHS = BinOp->getRHS()) {
11932 RHS = RHS->IgnoreParenCasts();
11933 llvm::APSInt Value;
11934 VarWillBeReased =
11935 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11936 }
11937 }
11938 }
John McCall31168b02011-06-15 23:02:42 +000011939 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011940
11941} // namespace
John McCall31168b02011-06-15 23:02:42 +000011942
11943/// Check whether the given argument is a block which captures a
11944/// variable.
11945static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11946 assert(owner.Variable && owner.Loc.isValid());
11947
11948 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011949
11950 // Look through [^{...} copy] and Block_copy(^{...}).
11951 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11952 Selector Cmd = ME->getSelector();
11953 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11954 e = ME->getInstanceReceiver();
11955 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011956 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011957 e = e->IgnoreParenCasts();
11958 }
11959 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11960 if (CE->getNumArgs() == 1) {
11961 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011962 if (Fn) {
11963 const IdentifierInfo *FnI = Fn->getIdentifier();
11964 if (FnI && FnI->isStr("_Block_copy")) {
11965 e = CE->getArg(0)->IgnoreParenCasts();
11966 }
11967 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011968 }
11969 }
11970
John McCall31168b02011-06-15 23:02:42 +000011971 BlockExpr *block = dyn_cast<BlockExpr>(e);
11972 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011973 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011974
11975 FindCaptureVisitor visitor(S.Context, owner.Variable);
11976 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011977 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011978}
11979
11980static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11981 RetainCycleOwner &owner) {
11982 assert(capturer);
11983 assert(owner.Variable && owner.Loc.isValid());
11984
11985 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11986 << owner.Variable << capturer->getSourceRange();
11987 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11988 << owner.Indirect << owner.Range;
11989}
11990
11991/// Check for a keyword selector that starts with the word 'add' or
11992/// 'set'.
11993static bool isSetterLikeSelector(Selector sel) {
11994 if (sel.isUnarySelector()) return false;
11995
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011996 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011997 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011998 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011999 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012000 else if (str.startswith("add")) {
12001 // Specially whitelist 'addOperationWithBlock:'.
12002 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12003 return false;
12004 str = str.substr(3);
12005 }
John McCall31168b02011-06-15 23:02:42 +000012006 else
12007 return false;
12008
12009 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000012010 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000012011}
12012
Benjamin Kramer3a743452015-03-09 15:03:32 +000012013static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12014 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012015 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12016 Message->getReceiverInterface(),
12017 NSAPI::ClassId_NSMutableArray);
12018 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012019 return None;
12020 }
12021
12022 Selector Sel = Message->getSelector();
12023
12024 Optional<NSAPI::NSArrayMethodKind> MKOpt =
12025 S.NSAPIObj->getNSArrayMethodKind(Sel);
12026 if (!MKOpt) {
12027 return None;
12028 }
12029
12030 NSAPI::NSArrayMethodKind MK = *MKOpt;
12031
12032 switch (MK) {
12033 case NSAPI::NSMutableArr_addObject:
12034 case NSAPI::NSMutableArr_insertObjectAtIndex:
12035 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12036 return 0;
12037 case NSAPI::NSMutableArr_replaceObjectAtIndex:
12038 return 1;
12039
12040 default:
12041 return None;
12042 }
12043
12044 return None;
12045}
12046
12047static
12048Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12049 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012050 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12051 Message->getReceiverInterface(),
12052 NSAPI::ClassId_NSMutableDictionary);
12053 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012054 return None;
12055 }
12056
12057 Selector Sel = Message->getSelector();
12058
12059 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12060 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12061 if (!MKOpt) {
12062 return None;
12063 }
12064
12065 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12066
12067 switch (MK) {
12068 case NSAPI::NSMutableDict_setObjectForKey:
12069 case NSAPI::NSMutableDict_setValueForKey:
12070 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12071 return 0;
12072
12073 default:
12074 return None;
12075 }
12076
12077 return None;
12078}
12079
12080static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012081 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12082 Message->getReceiverInterface(),
12083 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012084
Alex Denisov5dfac812015-08-06 04:51:14 +000012085 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12086 Message->getReceiverInterface(),
12087 NSAPI::ClassId_NSMutableOrderedSet);
12088 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012089 return None;
12090 }
12091
12092 Selector Sel = Message->getSelector();
12093
12094 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12095 if (!MKOpt) {
12096 return None;
12097 }
12098
12099 NSAPI::NSSetMethodKind MK = *MKOpt;
12100
12101 switch (MK) {
12102 case NSAPI::NSMutableSet_addObject:
12103 case NSAPI::NSOrderedSet_setObjectAtIndex:
12104 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12105 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12106 return 0;
12107 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12108 return 1;
12109 }
12110
12111 return None;
12112}
12113
12114void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12115 if (!Message->isInstanceMessage()) {
12116 return;
12117 }
12118
12119 Optional<int> ArgOpt;
12120
12121 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12122 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12123 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12124 return;
12125 }
12126
12127 int ArgIndex = *ArgOpt;
12128
Alex Denisove1d882c2015-03-04 17:55:52 +000012129 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12130 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12131 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12132 }
12133
Alex Denisov5dfac812015-08-06 04:51:14 +000012134 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012135 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012136 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012137 Diag(Message->getSourceRange().getBegin(),
12138 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012139 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012140 }
12141 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012142 } else {
12143 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12144
12145 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12146 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12147 }
12148
12149 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12150 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12151 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12152 ValueDecl *Decl = ReceiverRE->getDecl();
12153 Diag(Message->getSourceRange().getBegin(),
12154 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012155 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012156 if (!ArgRE->isObjCSelfExpr()) {
12157 Diag(Decl->getLocation(),
12158 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012159 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012160 }
12161 }
12162 }
12163 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12164 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12165 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12166 ObjCIvarDecl *Decl = IvarRE->getDecl();
12167 Diag(Message->getSourceRange().getBegin(),
12168 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012169 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012170 Diag(Decl->getLocation(),
12171 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012172 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012173 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012174 }
12175 }
12176 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012177}
12178
John McCall31168b02011-06-15 23:02:42 +000012179/// Check a message send to see if it's likely to cause a retain cycle.
12180void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12181 // Only check instance methods whose selector looks like a setter.
12182 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12183 return;
12184
12185 // Try to find a variable that the receiver is strongly owned by.
12186 RetainCycleOwner owner;
12187 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012188 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012189 return;
12190 } else {
12191 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12192 owner.Variable = getCurMethodDecl()->getSelfDecl();
12193 owner.Loc = msg->getSuperLoc();
12194 owner.Range = msg->getSuperLoc();
12195 }
12196
12197 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012198 const ObjCMethodDecl *MD = msg->getMethodDecl();
12199 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12200 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12201 // noescape blocks should not be retained by the method.
12202 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12203 continue;
John McCall31168b02011-06-15 23:02:42 +000012204 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012205 }
12206 }
John McCall31168b02011-06-15 23:02:42 +000012207}
12208
12209/// Check a property assign to see if it's likely to cause a retain cycle.
12210void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12211 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012212 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012213 return;
12214
12215 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12216 diagnoseRetainCycle(*this, capturer, owner);
12217}
12218
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012219void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12220 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012221 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012222 return;
12223
12224 // Because we don't have an expression for the variable, we have to set the
12225 // location explicitly here.
12226 Owner.Loc = Var->getLocation();
12227 Owner.Range = Var->getSourceRange();
12228
12229 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12230 diagnoseRetainCycle(*this, Capturer, Owner);
12231}
12232
Ted Kremenek9304da92012-12-21 08:04:28 +000012233static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12234 Expr *RHS, bool isProperty) {
12235 // Check if RHS is an Objective-C object literal, which also can get
12236 // immediately zapped in a weak reference. Note that we explicitly
12237 // allow ObjCStringLiterals, since those are designed to never really die.
12238 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012239
Ted Kremenek64873352012-12-21 22:46:35 +000012240 // This enum needs to match with the 'select' in
12241 // warn_objc_arc_literal_assign (off-by-1).
12242 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12243 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12244 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012245
12246 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012247 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012248 << (isProperty ? 0 : 1)
12249 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012250
12251 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012252}
12253
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012254static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12255 Qualifiers::ObjCLifetime LT,
12256 Expr *RHS, bool isProperty) {
12257 // Strip off any implicit cast added to get to the one ARC-specific.
12258 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12259 if (cast->getCastKind() == CK_ARCConsumeObject) {
12260 S.Diag(Loc, diag::warn_arc_retained_assign)
12261 << (LT == Qualifiers::OCL_ExplicitNone)
12262 << (isProperty ? 0 : 1)
12263 << RHS->getSourceRange();
12264 return true;
12265 }
12266 RHS = cast->getSubExpr();
12267 }
12268
12269 if (LT == Qualifiers::OCL_Weak &&
12270 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12271 return true;
12272
12273 return false;
12274}
12275
Ted Kremenekb36234d2012-12-21 08:04:20 +000012276bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12277 QualType LHS, Expr *RHS) {
12278 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12279
12280 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12281 return false;
12282
12283 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12284 return true;
12285
12286 return false;
12287}
12288
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012289void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12290 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012291 QualType LHSType;
12292 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012293 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012294 ObjCPropertyRefExpr *PRE
12295 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12296 if (PRE && !PRE->isImplicitProperty()) {
12297 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12298 if (PD)
12299 LHSType = PD->getType();
12300 }
12301
12302 if (LHSType.isNull())
12303 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012304
12305 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12306
12307 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012308 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012309 getCurFunction()->markSafeWeakUse(LHS);
12310 }
12311
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012312 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12313 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012314
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012315 // FIXME. Check for other life times.
12316 if (LT != Qualifiers::OCL_None)
12317 return;
12318
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012319 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012320 if (PRE->isImplicitProperty())
12321 return;
12322 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12323 if (!PD)
12324 return;
12325
Bill Wendling44426052012-12-20 19:22:21 +000012326 unsigned Attributes = PD->getPropertyAttributes();
12327 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012328 // when 'assign' attribute was not explicitly specified
12329 // by user, ignore it and rely on property type itself
12330 // for lifetime info.
12331 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12332 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12333 LHSType->isObjCRetainableType())
12334 return;
12335
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012336 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012337 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012338 Diag(Loc, diag::warn_arc_retained_property_assign)
12339 << RHS->getSourceRange();
12340 return;
12341 }
12342 RHS = cast->getSubExpr();
12343 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012344 }
Bill Wendling44426052012-12-20 19:22:21 +000012345 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012346 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12347 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012348 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012349 }
12350}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012351
12352//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12353
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012354static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12355 SourceLocation StmtLoc,
12356 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012357 // Do not warn if the body is a macro that expands to nothing, e.g:
12358 //
12359 // #define CALL(x)
12360 // if (condition)
12361 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012362 if (Body->hasLeadingEmptyMacro())
12363 return false;
12364
12365 // Get line numbers of statement and body.
12366 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012367 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012368 &StmtLineInvalid);
12369 if (StmtLineInvalid)
12370 return false;
12371
12372 bool BodyLineInvalid;
12373 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12374 &BodyLineInvalid);
12375 if (BodyLineInvalid)
12376 return false;
12377
12378 // Warn if null statement and body are on the same line.
12379 if (StmtLine != BodyLine)
12380 return false;
12381
12382 return true;
12383}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012384
12385void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12386 const Stmt *Body,
12387 unsigned DiagID) {
12388 // Since this is a syntactic check, don't emit diagnostic for template
12389 // instantiations, this just adds noise.
12390 if (CurrentInstantiationScope)
12391 return;
12392
12393 // The body should be a null statement.
12394 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12395 if (!NBody)
12396 return;
12397
12398 // Do the usual checks.
12399 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12400 return;
12401
12402 Diag(NBody->getSemiLoc(), DiagID);
12403 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12404}
12405
12406void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12407 const Stmt *PossibleBody) {
12408 assert(!CurrentInstantiationScope); // Ensured by caller
12409
12410 SourceLocation StmtLoc;
12411 const Stmt *Body;
12412 unsigned DiagID;
12413 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12414 StmtLoc = FS->getRParenLoc();
12415 Body = FS->getBody();
12416 DiagID = diag::warn_empty_for_body;
12417 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12418 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12419 Body = WS->getBody();
12420 DiagID = diag::warn_empty_while_body;
12421 } else
12422 return; // Neither `for' nor `while'.
12423
12424 // The body should be a null statement.
12425 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12426 if (!NBody)
12427 return;
12428
12429 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012430 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012431 return;
12432
12433 // Do the usual checks.
12434 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12435 return;
12436
12437 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12438 // noise level low, emit diagnostics only if for/while is followed by a
12439 // CompoundStmt, e.g.:
12440 // for (int i = 0; i < n; i++);
12441 // {
12442 // a(i);
12443 // }
12444 // or if for/while is followed by a statement with more indentation
12445 // than for/while itself:
12446 // for (int i = 0; i < n; i++);
12447 // a(i);
12448 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12449 if (!ProbableTypo) {
12450 bool BodyColInvalid;
12451 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12452 PossibleBody->getLocStart(),
12453 &BodyColInvalid);
12454 if (BodyColInvalid)
12455 return;
12456
12457 bool StmtColInvalid;
12458 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12459 S->getLocStart(),
12460 &StmtColInvalid);
12461 if (StmtColInvalid)
12462 return;
12463
12464 if (BodyCol > StmtCol)
12465 ProbableTypo = true;
12466 }
12467
12468 if (ProbableTypo) {
12469 Diag(NBody->getSemiLoc(), DiagID);
12470 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12471 }
12472}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012473
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012474//===--- CHECK: Warn on self move with std::move. -------------------------===//
12475
12476/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12477void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12478 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012479 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12480 return;
12481
Richard Smith51ec0cf2017-02-21 01:17:38 +000012482 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012483 return;
12484
12485 // Strip parens and casts away.
12486 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12487 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12488
12489 // Check for a call expression
12490 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12491 if (!CE || CE->getNumArgs() != 1)
12492 return;
12493
12494 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012495 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012496 return;
12497
12498 // Get argument from std::move
12499 RHSExpr = CE->getArg(0);
12500
12501 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12502 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12503
12504 // Two DeclRefExpr's, check that the decls are the same.
12505 if (LHSDeclRef && RHSDeclRef) {
12506 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12507 return;
12508 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12509 RHSDeclRef->getDecl()->getCanonicalDecl())
12510 return;
12511
12512 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12513 << LHSExpr->getSourceRange()
12514 << RHSExpr->getSourceRange();
12515 return;
12516 }
12517
12518 // Member variables require a different approach to check for self moves.
12519 // MemberExpr's are the same if every nested MemberExpr refers to the same
12520 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12521 // the base Expr's are CXXThisExpr's.
12522 const Expr *LHSBase = LHSExpr;
12523 const Expr *RHSBase = RHSExpr;
12524 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12525 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12526 if (!LHSME || !RHSME)
12527 return;
12528
12529 while (LHSME && RHSME) {
12530 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12531 RHSME->getMemberDecl()->getCanonicalDecl())
12532 return;
12533
12534 LHSBase = LHSME->getBase();
12535 RHSBase = RHSME->getBase();
12536 LHSME = dyn_cast<MemberExpr>(LHSBase);
12537 RHSME = dyn_cast<MemberExpr>(RHSBase);
12538 }
12539
12540 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12541 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12542 if (LHSDeclRef && RHSDeclRef) {
12543 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12544 return;
12545 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12546 RHSDeclRef->getDecl()->getCanonicalDecl())
12547 return;
12548
12549 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12550 << LHSExpr->getSourceRange()
12551 << RHSExpr->getSourceRange();
12552 return;
12553 }
12554
12555 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12556 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12557 << LHSExpr->getSourceRange()
12558 << RHSExpr->getSourceRange();
12559}
12560
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012561//===--- Layout compatibility ----------------------------------------------//
12562
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012563static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012564
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012565/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012566static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012567 // C++11 [dcl.enum] p8:
12568 // Two enumeration types are layout-compatible if they have the same
12569 // underlying type.
12570 return ED1->isComplete() && ED2->isComplete() &&
12571 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12572}
12573
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012574/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012575static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12576 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012577 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12578 return false;
12579
12580 if (Field1->isBitField() != Field2->isBitField())
12581 return false;
12582
12583 if (Field1->isBitField()) {
12584 // Make sure that the bit-fields are the same length.
12585 unsigned Bits1 = Field1->getBitWidthValue(C);
12586 unsigned Bits2 = Field2->getBitWidthValue(C);
12587
12588 if (Bits1 != Bits2)
12589 return false;
12590 }
12591
12592 return true;
12593}
12594
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012595/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012596/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012597static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12598 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012599 // If both records are C++ classes, check that base classes match.
12600 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12601 // If one of records is a CXXRecordDecl we are in C++ mode,
12602 // thus the other one is a CXXRecordDecl, too.
12603 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12604 // Check number of base classes.
12605 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12606 return false;
12607
12608 // Check the base classes.
12609 for (CXXRecordDecl::base_class_const_iterator
12610 Base1 = D1CXX->bases_begin(),
12611 BaseEnd1 = D1CXX->bases_end(),
12612 Base2 = D2CXX->bases_begin();
12613 Base1 != BaseEnd1;
12614 ++Base1, ++Base2) {
12615 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12616 return false;
12617 }
12618 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12619 // If only RD2 is a C++ class, it should have zero base classes.
12620 if (D2CXX->getNumBases() > 0)
12621 return false;
12622 }
12623
12624 // Check the fields.
12625 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12626 Field2End = RD2->field_end(),
12627 Field1 = RD1->field_begin(),
12628 Field1End = RD1->field_end();
12629 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12630 if (!isLayoutCompatible(C, *Field1, *Field2))
12631 return false;
12632 }
12633 if (Field1 != Field1End || Field2 != Field2End)
12634 return false;
12635
12636 return true;
12637}
12638
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012639/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012640/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012641static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12642 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012643 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012644 for (auto *Field2 : RD2->fields())
12645 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012646
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012647 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012648 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12649 I = UnmatchedFields.begin(),
12650 E = UnmatchedFields.end();
12651
12652 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012653 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012654 bool Result = UnmatchedFields.erase(*I);
12655 (void) Result;
12656 assert(Result);
12657 break;
12658 }
12659 }
12660 if (I == E)
12661 return false;
12662 }
12663
12664 return UnmatchedFields.empty();
12665}
12666
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012667static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12668 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012669 if (RD1->isUnion() != RD2->isUnion())
12670 return false;
12671
12672 if (RD1->isUnion())
12673 return isLayoutCompatibleUnion(C, RD1, RD2);
12674 else
12675 return isLayoutCompatibleStruct(C, RD1, RD2);
12676}
12677
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012678/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012679static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012680 if (T1.isNull() || T2.isNull())
12681 return false;
12682
12683 // C++11 [basic.types] p11:
12684 // If two types T1 and T2 are the same type, then T1 and T2 are
12685 // layout-compatible types.
12686 if (C.hasSameType(T1, T2))
12687 return true;
12688
12689 T1 = T1.getCanonicalType().getUnqualifiedType();
12690 T2 = T2.getCanonicalType().getUnqualifiedType();
12691
12692 const Type::TypeClass TC1 = T1->getTypeClass();
12693 const Type::TypeClass TC2 = T2->getTypeClass();
12694
12695 if (TC1 != TC2)
12696 return false;
12697
12698 if (TC1 == Type::Enum) {
12699 return isLayoutCompatible(C,
12700 cast<EnumType>(T1)->getDecl(),
12701 cast<EnumType>(T2)->getDecl());
12702 } else if (TC1 == Type::Record) {
12703 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12704 return false;
12705
12706 return isLayoutCompatible(C,
12707 cast<RecordType>(T1)->getDecl(),
12708 cast<RecordType>(T2)->getDecl());
12709 }
12710
12711 return false;
12712}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012713
12714//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12715
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012716/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012717///
12718/// \param TypeExpr Type tag expression, as it appears in user's code.
12719///
12720/// \param VD Declaration of an identifier that appears in a type tag.
12721///
12722/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012723static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12724 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012725 while(true) {
12726 if (!TypeExpr)
12727 return false;
12728
12729 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12730
12731 switch (TypeExpr->getStmtClass()) {
12732 case Stmt::UnaryOperatorClass: {
12733 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12734 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12735 TypeExpr = UO->getSubExpr();
12736 continue;
12737 }
12738 return false;
12739 }
12740
12741 case Stmt::DeclRefExprClass: {
12742 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12743 *VD = DRE->getDecl();
12744 return true;
12745 }
12746
12747 case Stmt::IntegerLiteralClass: {
12748 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12749 llvm::APInt MagicValueAPInt = IL->getValue();
12750 if (MagicValueAPInt.getActiveBits() <= 64) {
12751 *MagicValue = MagicValueAPInt.getZExtValue();
12752 return true;
12753 } else
12754 return false;
12755 }
12756
12757 case Stmt::BinaryConditionalOperatorClass:
12758 case Stmt::ConditionalOperatorClass: {
12759 const AbstractConditionalOperator *ACO =
12760 cast<AbstractConditionalOperator>(TypeExpr);
12761 bool Result;
12762 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12763 if (Result)
12764 TypeExpr = ACO->getTrueExpr();
12765 else
12766 TypeExpr = ACO->getFalseExpr();
12767 continue;
12768 }
12769 return false;
12770 }
12771
12772 case Stmt::BinaryOperatorClass: {
12773 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12774 if (BO->getOpcode() == BO_Comma) {
12775 TypeExpr = BO->getRHS();
12776 continue;
12777 }
12778 return false;
12779 }
12780
12781 default:
12782 return false;
12783 }
12784 }
12785}
12786
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012787/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012788///
12789/// \param TypeExpr Expression that specifies a type tag.
12790///
12791/// \param MagicValues Registered magic values.
12792///
12793/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12794/// kind.
12795///
12796/// \param TypeInfo Information about the corresponding C type.
12797///
12798/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012799static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012800 const IdentifierInfo *ArgumentKind,
12801 const Expr *TypeExpr, const ASTContext &Ctx,
12802 const llvm::DenseMap<Sema::TypeTagMagicValue,
12803 Sema::TypeTagData> *MagicValues,
12804 bool &FoundWrongKind,
12805 Sema::TypeTagData &TypeInfo) {
12806 FoundWrongKind = false;
12807
12808 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012809 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012810
12811 uint64_t MagicValue;
12812
12813 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12814 return false;
12815
12816 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012817 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012818 if (I->getArgumentKind() != ArgumentKind) {
12819 FoundWrongKind = true;
12820 return false;
12821 }
12822 TypeInfo.Type = I->getMatchingCType();
12823 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12824 TypeInfo.MustBeNull = I->getMustBeNull();
12825 return true;
12826 }
12827 return false;
12828 }
12829
12830 if (!MagicValues)
12831 return false;
12832
12833 llvm::DenseMap<Sema::TypeTagMagicValue,
12834 Sema::TypeTagData>::const_iterator I =
12835 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12836 if (I == MagicValues->end())
12837 return false;
12838
12839 TypeInfo = I->second;
12840 return true;
12841}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012842
12843void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12844 uint64_t MagicValue, QualType Type,
12845 bool LayoutCompatible,
12846 bool MustBeNull) {
12847 if (!TypeTagForDatatypeMagicValues)
12848 TypeTagForDatatypeMagicValues.reset(
12849 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12850
12851 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12852 (*TypeTagForDatatypeMagicValues)[Magic] =
12853 TypeTagData(Type, LayoutCompatible, MustBeNull);
12854}
12855
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012856static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012857 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12858 if (!BT1)
12859 return false;
12860
12861 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12862 if (!BT2)
12863 return false;
12864
12865 BuiltinType::Kind T1Kind = BT1->getKind();
12866 BuiltinType::Kind T2Kind = BT2->getKind();
12867
12868 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12869 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12870 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12871 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12872}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012873
12874void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012875 const ArrayRef<const Expr *> ExprArgs,
12876 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012877 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12878 bool IsPointerAttr = Attr->getIsPointer();
12879
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012880 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012881 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12882 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012883 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012884 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012885 return;
12886 }
Joel E. Denny81508102018-03-13 14:51:22 +000012887 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012888 bool FoundWrongKind;
12889 TypeTagData TypeInfo;
12890 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12891 TypeTagForDatatypeMagicValues.get(),
12892 FoundWrongKind, TypeInfo)) {
12893 if (FoundWrongKind)
12894 Diag(TypeTagExpr->getExprLoc(),
12895 diag::warn_type_tag_for_datatype_wrong_kind)
12896 << TypeTagExpr->getSourceRange();
12897 return;
12898 }
12899
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012900 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012901 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12902 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012903 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012904 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012905 return;
12906 }
Joel E. Denny81508102018-03-13 14:51:22 +000012907 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012908 if (IsPointerAttr) {
12909 // Skip implicit cast of pointer to `void *' (as a function argument).
12910 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012911 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012912 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012913 ArgumentExpr = ICE->getSubExpr();
12914 }
12915 QualType ArgumentType = ArgumentExpr->getType();
12916
12917 // Passing a `void*' pointer shouldn't trigger a warning.
12918 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12919 return;
12920
12921 if (TypeInfo.MustBeNull) {
12922 // Type tag with matching void type requires a null pointer.
12923 if (!ArgumentExpr->isNullPointerConstant(Context,
12924 Expr::NPC_ValueDependentIsNotNull)) {
12925 Diag(ArgumentExpr->getExprLoc(),
12926 diag::warn_type_safety_null_pointer_required)
12927 << ArgumentKind->getName()
12928 << ArgumentExpr->getSourceRange()
12929 << TypeTagExpr->getSourceRange();
12930 }
12931 return;
12932 }
12933
12934 QualType RequiredType = TypeInfo.Type;
12935 if (IsPointerAttr)
12936 RequiredType = Context.getPointerType(RequiredType);
12937
12938 bool mismatch = false;
12939 if (!TypeInfo.LayoutCompatible) {
12940 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12941
12942 // C++11 [basic.fundamental] p1:
12943 // Plain char, signed char, and unsigned char are three distinct types.
12944 //
12945 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12946 // char' depending on the current char signedness mode.
12947 if (mismatch)
12948 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12949 RequiredType->getPointeeType())) ||
12950 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12951 mismatch = false;
12952 } else
12953 if (IsPointerAttr)
12954 mismatch = !isLayoutCompatible(Context,
12955 ArgumentType->getPointeeType(),
12956 RequiredType->getPointeeType());
12957 else
12958 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12959
12960 if (mismatch)
12961 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012962 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012963 << TypeInfo.LayoutCompatible << RequiredType
12964 << ArgumentExpr->getSourceRange()
12965 << TypeTagExpr->getSourceRange();
12966}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012967
12968void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12969 CharUnits Alignment) {
12970 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12971}
12972
12973void Sema::DiagnoseMisalignedMembers() {
12974 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012975 const NamedDecl *ND = m.RD;
12976 if (ND->getName().empty()) {
12977 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12978 ND = TD;
12979 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012980 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012981 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012982 }
12983 MisalignedMembers.clear();
12984}
12985
12986void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012987 E = E->IgnoreParens();
12988 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012989 return;
12990 if (isa<UnaryOperator>(E) &&
12991 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12992 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12993 if (isa<MemberExpr>(Op)) {
12994 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12995 MisalignedMember(Op));
12996 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012997 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012998 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12999 Context.getTypeAlignInChars(
13000 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013001 MisalignedMembers.erase(MA);
13002 }
13003 }
13004}
13005
13006void Sema::RefersToMemberWithReducedAlignment(
13007 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000013008 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13009 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013010 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013011 if (!ME)
13012 return;
13013
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000013014 // No need to check expressions with an __unaligned-qualified type.
13015 if (E->getType().getQualifiers().hasUnaligned())
13016 return;
13017
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013018 // For a chain of MemberExpr like "a.b.c.d" this list
13019 // will keep FieldDecl's like [d, c, b].
13020 SmallVector<FieldDecl *, 4> ReverseMemberChain;
13021 const MemberExpr *TopME = nullptr;
13022 bool AnyIsPacked = false;
13023 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013024 QualType BaseType = ME->getBase()->getType();
13025 if (ME->isArrow())
13026 BaseType = BaseType->getPointeeType();
13027 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000013028 if (RD->isInvalidDecl())
13029 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013030
13031 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013032 auto *FD = dyn_cast<FieldDecl>(MD);
13033 // We do not care about non-data members.
13034 if (!FD || FD->isInvalidDecl())
13035 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013036
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013037 AnyIsPacked =
13038 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13039 ReverseMemberChain.push_back(FD);
13040
13041 TopME = ME;
13042 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13043 } while (ME);
13044 assert(TopME && "We did not compute a topmost MemberExpr!");
13045
13046 // Not the scope of this diagnostic.
13047 if (!AnyIsPacked)
13048 return;
13049
13050 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13051 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13052 // TODO: The innermost base of the member expression may be too complicated.
13053 // For now, just disregard these cases. This is left for future
13054 // improvement.
13055 if (!DRE && !isa<CXXThisExpr>(TopBase))
13056 return;
13057
13058 // Alignment expected by the whole expression.
13059 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13060
13061 // No need to do anything else with this case.
13062 if (ExpectedAlignment.isOne())
13063 return;
13064
13065 // Synthesize offset of the whole access.
13066 CharUnits Offset;
13067 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13068 I++) {
13069 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13070 }
13071
13072 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13073 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13074 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13075
13076 // The base expression of the innermost MemberExpr may give
13077 // stronger guarantees than the class containing the member.
13078 if (DRE && !TopME->isArrow()) {
13079 const ValueDecl *VD = DRE->getDecl();
13080 if (!VD->getType()->isReferenceType())
13081 CompleteObjectAlignment =
13082 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13083 }
13084
13085 // Check if the synthesized offset fulfills the alignment.
13086 if (Offset % ExpectedAlignment != 0 ||
13087 // It may fulfill the offset it but the effective alignment may still be
13088 // lower than the expected expression alignment.
13089 CompleteObjectAlignment < ExpectedAlignment) {
13090 // If this happens, we want to determine a sensible culprit of this.
13091 // Intuitively, watching the chain of member expressions from right to
13092 // left, we start with the required alignment (as required by the field
13093 // type) but some packed attribute in that chain has reduced the alignment.
13094 // It may happen that another packed structure increases it again. But if
13095 // we are here such increase has not been enough. So pointing the first
13096 // FieldDecl that either is packed or else its RecordDecl is,
13097 // seems reasonable.
13098 FieldDecl *FD = nullptr;
13099 CharUnits Alignment;
13100 for (FieldDecl *FDI : ReverseMemberChain) {
13101 if (FDI->hasAttr<PackedAttr>() ||
13102 FDI->getParent()->hasAttr<PackedAttr>()) {
13103 FD = FDI;
13104 Alignment = std::min(
13105 Context.getTypeAlignInChars(FD->getType()),
13106 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13107 break;
13108 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013109 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013110 assert(FD && "We did not find a packed FieldDecl!");
13111 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013112 }
13113}
13114
13115void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13116 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013117
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013118 RefersToMemberWithReducedAlignment(
13119 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13120 _2, _3, _4));
13121}