blob: e18dd056e90b4e342875de41a6c7ac512a15e0ec [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
Aaron Ballman9360cb02018-06-19 14:36:04 +0000775 // 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
779 return false;
780}
781
782// Performs a semantic analysis on {work_group_/sub_group_
783// /_}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
794 // Check reserve_id_t.
795 if (!Call->getArg(1)->getType()->isReserveIDT()) {
796 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
797 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
798 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
799 return true;
800 }
801
802 return false;
803}
804
805// Performs a semantic analysis on the call to built-in Pipe
806// 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)
816 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
817 return true;
818 }
819
820 return false;
821}
822
823// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
824// Performs semantic analysis for the to_global/local/private call.
825// \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) {
831 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;
854 case Builtin::BIto_private:
855 Qual.setAddressSpace(LangAS::opencl_private);
856 break;
857 default:
858 llvm_unreachable("Invalid builtin function");
859 }
860 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
861 RT.getUnqualifiedType(), Qual)));
862
863 return false;
864}
865
866// 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
880ExprResult
881Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
882 CallExpr *TheCall) {
883 ExprResult TheCallResult(TheCall);
884
885 // 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
903 switch (BuiltinID) {
904 case Builtin::BI__builtin___CFStringMakeConstantString:
905 assert(TheCall->getNumArgs() == 1 &&
906 "Wrong # arguments to builtin CFStringMakeConstantString");
907 if (CheckObjCString(TheCall->getArg(0)))
908 return ExprError();
909 break;
910 case Builtin::BI__builtin_ms_va_start:
911 case Builtin::BI__builtin_stdarg_start:
912 case Builtin::BI__builtin_va_start:
913 if (SemaBuiltinVAStart(BuiltinID, TheCall))
914 return ExprError();
915 break;
916 case Builtin::BI__va_start: {
917 switch (Context.getTargetInfo().getTriple().getArch()) {
918 case llvm::Triple::arm:
919 case llvm::Triple::thumb:
920 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
921 return ExprError();
922 break;
923 default:
924 if (SemaBuiltinVAStart(BuiltinID, TheCall))
925 return ExprError();
926 break;
927 }
928 break;
929 }
930
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
957 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:
963 if (SemaBuiltinUnorderedCompare(TheCall))
964 return ExprError();
965 break;
966 case Builtin::BI__builtin_fpclassify:
967 if (SemaBuiltinFPClassification(TheCall, 6))
968 return ExprError();
969 break;
970 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:
975 case Builtin::BI__builtin_signbit:
976 case Builtin::BI__builtin_signbitf:
977 case Builtin::BI__builtin_signbitl:
978 if (SemaBuiltinFPClassification(TheCall, 1))
979 return ExprError();
980 break;
981 case Builtin::BI__builtin_shufflevector:
982 return SemaBuiltinShuffleVector(TheCall);
983 // TheCall will be freed by the smart pointer here, but that's fine, since
984 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
985 case Builtin::BI__builtin_prefetch:
986 if (SemaBuiltinPrefetch(TheCall))
987 return ExprError();
988 break;
989 case Builtin::BI__builtin_alloca_with_align:
990 if (SemaBuiltinAllocaWithAlign(TheCall))
991 return ExprError();
992 break;
993 case Builtin::BI__assume:
994 case Builtin::BI__builtin_assume:
995 if (SemaBuiltinAssume(TheCall))
996 return ExprError();
997 break;
998 case Builtin::BI__builtin_assume_aligned:
999 if (SemaBuiltinAssumeAligned(TheCall))
1000 return ExprError();
1001 break;
1002 case Builtin::BI__builtin_object_size:
1003 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1004 return ExprError();
1005 break;
1006 case Builtin::BI__builtin_longjmp:
1007 if (SemaBuiltinLongjmp(TheCall))
1008 return ExprError();
1009 break;
1010 case Builtin::BI__builtin_setjmp:
1011 if (SemaBuiltinSetjmp(TheCall))
1012 return ExprError();
1013 break;
1014 case Builtin::BI_setjmp:
1015 case Builtin::BI_setjmpex:
1016 if (checkArgCount(*this, TheCall, 1))
1017 return true;
1018 break;
1019 case Builtin::BI__builtin_classify_type:
1020 if (checkArgCount(*this, TheCall, 1)) return true;
1021 TheCall->setType(Context.IntTy);
1022 break;
1023 case Builtin::BI__builtin_constant_p:
1024 if (checkArgCount(*this, TheCall, 1)) return true;
1025 TheCall->setType(Context.IntTy);
1026 break;
1027 case Builtin::BI__sync_fetch_and_add:
1028 case Builtin::BI__sync_fetch_and_add_1:
1029 case Builtin::BI__sync_fetch_and_add_2:
1030 case Builtin::BI__sync_fetch_and_add_4:
1031 case Builtin::BI__sync_fetch_and_add_8:
1032 case Builtin::BI__sync_fetch_and_add_16:
1033 case Builtin::BI__sync_fetch_and_sub:
1034 case Builtin::BI__sync_fetch_and_sub_1:
1035 case Builtin::BI__sync_fetch_and_sub_2:
1036 case Builtin::BI__sync_fetch_and_sub_4:
1037 case Builtin::BI__sync_fetch_and_sub_8:
1038 case Builtin::BI__sync_fetch_and_sub_16:
1039 case Builtin::BI__sync_fetch_and_or:
1040 case Builtin::BI__sync_fetch_and_or_1:
1041 case Builtin::BI__sync_fetch_and_or_2:
1042 case Builtin::BI__sync_fetch_and_or_4:
1043 case Builtin::BI__sync_fetch_and_or_8:
1044 case Builtin::BI__sync_fetch_and_or_16:
1045 case Builtin::BI__sync_fetch_and_and:
1046 case Builtin::BI__sync_fetch_and_and_1:
1047 case Builtin::BI__sync_fetch_and_and_2:
1048 case Builtin::BI__sync_fetch_and_and_4:
1049 case Builtin::BI__sync_fetch_and_and_8:
1050 case Builtin::BI__sync_fetch_and_and_16:
1051 case Builtin::BI__sync_fetch_and_xor:
1052 case Builtin::BI__sync_fetch_and_xor_1:
1053 case Builtin::BI__sync_fetch_and_xor_2:
1054 case Builtin::BI__sync_fetch_and_xor_4:
1055 case Builtin::BI__sync_fetch_and_xor_8:
1056 case Builtin::BI__sync_fetch_and_xor_16:
1057 case Builtin::BI__sync_fetch_and_nand:
1058 case Builtin::BI__sync_fetch_and_nand_1:
1059 case Builtin::BI__sync_fetch_and_nand_2:
1060 case Builtin::BI__sync_fetch_and_nand_4:
1061 case Builtin::BI__sync_fetch_and_nand_8:
1062 case Builtin::BI__sync_fetch_and_nand_16:
1063 case Builtin::BI__sync_add_and_fetch:
1064 case Builtin::BI__sync_add_and_fetch_1:
1065 case Builtin::BI__sync_add_and_fetch_2:
1066 case Builtin::BI__sync_add_and_fetch_4:
1067 case Builtin::BI__sync_add_and_fetch_8:
1068 case Builtin::BI__sync_add_and_fetch_16:
1069 case Builtin::BI__sync_sub_and_fetch:
1070 case Builtin::BI__sync_sub_and_fetch_1:
1071 case Builtin::BI__sync_sub_and_fetch_2:
1072 case Builtin::BI__sync_sub_and_fetch_4:
1073 case Builtin::BI__sync_sub_and_fetch_8:
1074 case Builtin::BI__sync_sub_and_fetch_16:
1075 case Builtin::BI__sync_and_and_fetch:
1076 case Builtin::BI__sync_and_and_fetch_1:
1077 case Builtin::BI__sync_and_and_fetch_2:
1078 case Builtin::BI__sync_and_and_fetch_4:
1079 case Builtin::BI__sync_and_and_fetch_8:
1080 case Builtin::BI__sync_and_and_fetch_16:
1081 case Builtin::BI__sync_or_and_fetch:
1082 case Builtin::BI__sync_or_and_fetch_1:
1083 case Builtin::BI__sync_or_and_fetch_2:
1084 case Builtin::BI__sync_or_and_fetch_4:
1085 case Builtin::BI__sync_or_and_fetch_8:
1086 case Builtin::BI__sync_or_and_fetch_16:
1087 case Builtin::BI__sync_xor_and_fetch:
1088 case Builtin::BI__sync_xor_and_fetch_1:
1089 case Builtin::BI__sync_xor_and_fetch_2:
1090 case Builtin::BI__sync_xor_and_fetch_4:
1091 case Builtin::BI__sync_xor_and_fetch_8:
1092 case Builtin::BI__sync_xor_and_fetch_16:
1093 case Builtin::BI__sync_nand_and_fetch:
1094 case Builtin::BI__sync_nand_and_fetch_1:
1095 case Builtin::BI__sync_nand_and_fetch_2:
1096 case Builtin::BI__sync_nand_and_fetch_4:
1097 case Builtin::BI__sync_nand_and_fetch_8:
1098 case Builtin::BI__sync_nand_and_fetch_16:
1099 case Builtin::BI__sync_val_compare_and_swap:
1100 case Builtin::BI__sync_val_compare_and_swap_1:
1101 case Builtin::BI__sync_val_compare_and_swap_2:
1102 case Builtin::BI__sync_val_compare_and_swap_4:
1103 case Builtin::BI__sync_val_compare_and_swap_8:
1104 case Builtin::BI__sync_val_compare_and_swap_16:
1105 case Builtin::BI__sync_bool_compare_and_swap:
1106 case Builtin::BI__sync_bool_compare_and_swap_1:
1107 case Builtin::BI__sync_bool_compare_and_swap_2:
1108 case Builtin::BI__sync_bool_compare_and_swap_4:
1109 case Builtin::BI__sync_bool_compare_and_swap_8:
1110 case Builtin::BI__sync_bool_compare_and_swap_16:
1111 case Builtin::BI__sync_lock_test_and_set:
1112 case Builtin::BI__sync_lock_test_and_set_1:
1113 case Builtin::BI__sync_lock_test_and_set_2:
1114 case Builtin::BI__sync_lock_test_and_set_4:
1115 case Builtin::BI__sync_lock_test_and_set_8:
1116 case Builtin::BI__sync_lock_test_and_set_16:
1117 case Builtin::BI__sync_lock_release:
1118 case Builtin::BI__sync_lock_release_1:
1119 case Builtin::BI__sync_lock_release_2:
1120 case Builtin::BI__sync_lock_release_4:
1121 case Builtin::BI__sync_lock_release_8:
1122 case Builtin::BI__sync_lock_release_16:
1123 case Builtin::BI__sync_swap:
1124 case Builtin::BI__sync_swap_1:
1125 case Builtin::BI__sync_swap_2:
1126 case Builtin::BI__sync_swap_4:
1127 case Builtin::BI__sync_swap_8:
1128 case Builtin::BI__sync_swap_16:
1129 return SemaBuiltinAtomicOverloaded(TheCallResult);
1130 case Builtin::BI__builtin_nontemporal_load:
1131 case Builtin::BI__builtin_nontemporal_store:
1132 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1133#define BUILTIN(ID, TYPE, ATTRS)
1134#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1135 case Builtin::BI##ID: \
1136 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1137#include "clang/Basic/Builtins.def"
1138 case Builtin::BI__annotation:
1139 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1140 return ExprError();
1141 break;
1142 case Builtin::BI__builtin_annotation:
1143 if (SemaBuiltinAnnotation(*this, TheCall))
1144 return ExprError();
1145 break;
1146 case Builtin::BI__builtin_addressof:
1147 if (SemaBuiltinAddressof(*this, TheCall))
1148 return ExprError();
1149 break;
1150 case Builtin::BI__builtin_add_overflow:
1151 case Builtin::BI__builtin_sub_overflow:
1152 case Builtin::BI__builtin_mul_overflow:
1153 if (SemaBuiltinOverflow(*this, TheCall))
1154 return ExprError();
1155 break;
1156 case Builtin::BI__builtin_operator_new:
1157 case Builtin::BI__builtin_operator_delete: {
1158 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1159 ExprResult Res =
1160 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1161 if (Res.isInvalid())
1162 CorrectDelayedTyposInExpr(TheCallResult.get());
1163 return Res;
1164 }
1165 case Builtin::BI__builtin_dump_struct: {
1166 // We first want to ensure we are called with 2 arguments
1167 if (checkArgCount(*this, TheCall, 2))
1168 return ExprError();
1169 // Ensure that the first argument is of type 'struct XX *'
1170 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1171 const QualType PtrArgType = PtrArg->getType();
1172 if (!PtrArgType->isPointerType() ||
1173 !PtrArgType->getPointeeType()->isRecordType()) {
1174 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1175 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1176 << "structure pointer";
1177 return ExprError();
Aaron Ballman06525342018-04-10 21:58:13 +00001178 }
1179
1180 // Ensure that the second argument is of type 'FunctionType'
1181 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1182 const QualType FnPtrArgType = FnPtrArg->getType();
1183 if (!FnPtrArgType->isPointerType()) {
1184 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1185 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1186 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1187 return ExprError();
1188 }
1189
1190 const auto *FuncType =
1191 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1192
1193 if (!FuncType) {
1194 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1195 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1196 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1197 return ExprError();
1198 }
1199
1200 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1201 if (!FT->getNumParams()) {
1202 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1203 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1204 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1205 return ExprError();
1206 }
1207 QualType PT = FT->getParamType(0);
1208 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1209 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1210 !PT->getPointeeType().isConstQualified()) {
1211 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1212 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1213 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1214 return ExprError();
1215 }
1216 }
1217
1218 TheCall->setType(Context.IntTy);
1219 break;
1220 }
1221
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001222 // check secure string manipulation functions where overflows
1223 // are detectable at compile time
1224 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001225 case Builtin::BI__builtin___memmove_chk:
1226 case Builtin::BI__builtin___memset_chk:
1227 case Builtin::BI__builtin___strlcat_chk:
1228 case Builtin::BI__builtin___strlcpy_chk:
1229 case Builtin::BI__builtin___strncat_chk:
1230 case Builtin::BI__builtin___strncpy_chk:
1231 case Builtin::BI__builtin___stpncpy_chk:
1232 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1233 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001234 case Builtin::BI__builtin___memccpy_chk:
1235 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1236 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001237 case Builtin::BI__builtin___snprintf_chk:
1238 case Builtin::BI__builtin___vsnprintf_chk:
1239 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1240 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001241 case Builtin::BI__builtin_call_with_static_chain:
1242 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1243 return ExprError();
1244 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001245 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001246 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001247 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1248 diag::err_seh___except_block))
1249 return ExprError();
1250 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001251 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001252 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001253 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1254 diag::err_seh___except_filter))
1255 return ExprError();
1256 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001257 case Builtin::BI__GetExceptionInfo:
1258 if (checkArgCount(*this, TheCall, 1))
1259 return ExprError();
1260
1261 if (CheckCXXThrowOperand(
1262 TheCall->getLocStart(),
1263 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1264 TheCall))
1265 return ExprError();
1266
1267 TheCall->setType(Context.VoidPtrTy);
1268 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001269 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001270 case Builtin::BIread_pipe:
1271 case Builtin::BIwrite_pipe:
1272 // Since those two functions are declared with var args, we need a semantic
1273 // check for the argument.
1274 if (SemaBuiltinRWPipe(*this, TheCall))
1275 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001276 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001277 break;
1278 case Builtin::BIreserve_read_pipe:
1279 case Builtin::BIreserve_write_pipe:
1280 case Builtin::BIwork_group_reserve_read_pipe:
1281 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001282 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1283 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001284 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001285 case Builtin::BIsub_group_reserve_read_pipe:
1286 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001287 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1288 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001289 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001290 break;
1291 case Builtin::BIcommit_read_pipe:
1292 case Builtin::BIcommit_write_pipe:
1293 case Builtin::BIwork_group_commit_read_pipe:
1294 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001295 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1296 return ExprError();
1297 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001298 case Builtin::BIsub_group_commit_read_pipe:
1299 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001300 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1301 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001302 return ExprError();
1303 break;
1304 case Builtin::BIget_pipe_num_packets:
1305 case Builtin::BIget_pipe_max_packets:
1306 if (SemaBuiltinPipePackets(*this, TheCall))
1307 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001308 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001309 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001310 case Builtin::BIto_global:
1311 case Builtin::BIto_local:
1312 case Builtin::BIto_private:
1313 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1314 return ExprError();
1315 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001316 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1317 case Builtin::BIenqueue_kernel:
1318 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1319 return ExprError();
1320 break;
1321 case Builtin::BIget_kernel_work_group_size:
1322 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1323 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1324 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001325 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001326 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1327 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1328 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1329 return ExprError();
1330 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001331 case Builtin::BI__builtin_os_log_format:
1332 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001333 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001334 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001335 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001336 }
Richard Smith760520b2014-06-03 23:27:44 +00001337
Nate Begeman4904e322010-06-08 02:47:44 +00001338 // Since the target specific builtins for each arch overlap, only check those
1339 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001340 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001341 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001342 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001343 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001344 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001345 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001346 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1347 return ExprError();
1348 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001349 case llvm::Triple::aarch64:
1350 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001351 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001352 return ExprError();
1353 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001354 case llvm::Triple::hexagon:
1355 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1356 return ExprError();
1357 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001358 case llvm::Triple::mips:
1359 case llvm::Triple::mipsel:
1360 case llvm::Triple::mips64:
1361 case llvm::Triple::mips64el:
1362 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1363 return ExprError();
1364 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001365 case llvm::Triple::systemz:
1366 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1367 return ExprError();
1368 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001369 case llvm::Triple::x86:
1370 case llvm::Triple::x86_64:
1371 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1372 return ExprError();
1373 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001374 case llvm::Triple::ppc:
1375 case llvm::Triple::ppc64:
1376 case llvm::Triple::ppc64le:
1377 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1378 return ExprError();
1379 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001380 default:
1381 break;
1382 }
1383 }
1384
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001385 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001386}
1387
Nate Begeman91e1fea2010-06-14 05:21:25 +00001388// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001389static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001390 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001391 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001392 switch (Type.getEltType()) {
1393 case NeonTypeFlags::Int8:
1394 case NeonTypeFlags::Poly8:
1395 return shift ? 7 : (8 << IsQuad) - 1;
1396 case NeonTypeFlags::Int16:
1397 case NeonTypeFlags::Poly16:
1398 return shift ? 15 : (4 << IsQuad) - 1;
1399 case NeonTypeFlags::Int32:
1400 return shift ? 31 : (2 << IsQuad) - 1;
1401 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001402 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001403 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001404 case NeonTypeFlags::Poly128:
1405 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001406 case NeonTypeFlags::Float16:
1407 assert(!shift && "cannot shift float types!");
1408 return (4 << IsQuad) - 1;
1409 case NeonTypeFlags::Float32:
1410 assert(!shift && "cannot shift float types!");
1411 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001412 case NeonTypeFlags::Float64:
1413 assert(!shift && "cannot shift float types!");
1414 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001415 }
David Blaikie8a40f702012-01-17 06:56:22 +00001416 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001417}
1418
Bob Wilsone4d77232011-11-08 05:04:11 +00001419/// getNeonEltType - Return the QualType corresponding to the elements of
1420/// the vector type specified by the NeonTypeFlags. This is used to check
1421/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001422static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001423 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001424 switch (Flags.getEltType()) {
1425 case NeonTypeFlags::Int8:
1426 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1427 case NeonTypeFlags::Int16:
1428 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1429 case NeonTypeFlags::Int32:
1430 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1431 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001432 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001433 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1434 else
1435 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1436 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001437 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001438 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001439 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001440 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001441 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001442 if (IsInt64Long)
1443 return Context.UnsignedLongTy;
1444 else
1445 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001446 case NeonTypeFlags::Poly128:
1447 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001448 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001449 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001450 case NeonTypeFlags::Float32:
1451 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001452 case NeonTypeFlags::Float64:
1453 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001454 }
David Blaikie8a40f702012-01-17 06:56:22 +00001455 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001456}
1457
Tim Northover12670412014-02-19 10:37:05 +00001458bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001459 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001460 uint64_t mask = 0;
1461 unsigned TV = 0;
1462 int PtrArgNum = -1;
1463 bool HasConstPtr = false;
1464 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001465#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001466#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001467#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001468#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001469 }
1470
1471 // For NEON intrinsics which are overloaded on vector element type, validate
1472 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001473 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001474 if (mask) {
1475 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1476 return true;
1477
1478 TV = Result.getLimitedValue(64);
1479 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1480 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001481 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001482 }
1483
1484 if (PtrArgNum >= 0) {
1485 // Check that pointer arguments have the specified type.
1486 Expr *Arg = TheCall->getArg(PtrArgNum);
1487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1488 Arg = ICE->getSubExpr();
1489 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1490 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001491
Tim Northovera2ee4332014-03-29 15:09:45 +00001492 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001493 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1494 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001495 bool IsInt64Long =
1496 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1497 QualType EltTy =
1498 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001499 if (HasConstPtr)
1500 EltTy = EltTy.withConst();
1501 QualType LHSTy = Context.getPointerType(EltTy);
1502 AssignConvertType ConvTy;
1503 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1504 if (RHS.isInvalid())
1505 return true;
1506 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1507 RHS.get(), AA_Assigning))
1508 return true;
1509 }
1510
1511 // For NEON intrinsics which take an immediate value as part of the
1512 // instruction, range check them here.
1513 unsigned i = 0, l = 0, u = 0;
1514 switch (BuiltinID) {
1515 default:
1516 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001517 #define GET_NEON_IMMEDIATE_CHECK
1518 #include "clang/Basic/arm_neon.inc"
1519 #include "clang/Basic/arm_fp16.inc"
1520 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001521 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001522
Richard Sandiford28940af2014-04-16 08:47:51 +00001523 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001524}
1525
Tim Northovera2ee4332014-03-29 15:09:45 +00001526bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1527 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001528 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001529 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001530 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001531 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001532 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001533 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1534 BuiltinID == AArch64::BI__builtin_arm_strex ||
1535 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001536 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001537 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001538 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1539 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1540 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001541
1542 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1543
1544 // Ensure that we have the proper number of arguments.
1545 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1546 return true;
1547
1548 // Inspect the pointer argument of the atomic builtin. This should always be
1549 // a pointer type, whose element is an integral scalar or pointer type.
1550 // Because it is a pointer type, we don't have to worry about any implicit
1551 // casts here.
1552 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1553 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1554 if (PointerArgRes.isInvalid())
1555 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001556 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001557
1558 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1559 if (!pointerType) {
1560 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1561 << PointerArg->getType() << PointerArg->getSourceRange();
1562 return true;
1563 }
1564
1565 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1566 // task is to insert the appropriate casts into the AST. First work out just
1567 // what the appropriate type is.
1568 QualType ValType = pointerType->getPointeeType();
1569 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1570 if (IsLdrex)
1571 AddrType.addConst();
1572
1573 // Issue a warning if the cast is dodgy.
1574 CastKind CastNeeded = CK_NoOp;
1575 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1576 CastNeeded = CK_BitCast;
1577 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1578 << PointerArg->getType()
1579 << Context.getPointerType(AddrType)
1580 << AA_Passing << PointerArg->getSourceRange();
1581 }
1582
1583 // Finally, do the cast and replace the argument with the corrected version.
1584 AddrType = Context.getPointerType(AddrType);
1585 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1586 if (PointerArgRes.isInvalid())
1587 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001588 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001589
1590 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1591
1592 // In general, we allow ints, floats and pointers to be loaded and stored.
1593 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1594 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1595 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1596 << PointerArg->getType() << PointerArg->getSourceRange();
1597 return true;
1598 }
1599
1600 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001601 if (Context.getTypeSize(ValType) > MaxWidth) {
1602 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001603 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1604 << PointerArg->getType() << PointerArg->getSourceRange();
1605 return true;
1606 }
1607
1608 switch (ValType.getObjCLifetime()) {
1609 case Qualifiers::OCL_None:
1610 case Qualifiers::OCL_ExplicitNone:
1611 // okay
1612 break;
1613
1614 case Qualifiers::OCL_Weak:
1615 case Qualifiers::OCL_Strong:
1616 case Qualifiers::OCL_Autoreleasing:
1617 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1618 << ValType << PointerArg->getSourceRange();
1619 return true;
1620 }
1621
Tim Northover6aacd492013-07-16 09:47:53 +00001622 if (IsLdrex) {
1623 TheCall->setType(ValType);
1624 return false;
1625 }
1626
1627 // Initialize the argument to be stored.
1628 ExprResult ValArg = TheCall->getArg(0);
1629 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1630 Context, ValType, /*consume*/ false);
1631 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1632 if (ValArg.isInvalid())
1633 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001634 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001635
1636 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1637 // but the custom checker bypasses all default analysis.
1638 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001639 return false;
1640}
1641
Nate Begeman4904e322010-06-08 02:47:44 +00001642bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001643 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001644 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1645 BuiltinID == ARM::BI__builtin_arm_strex ||
1646 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001647 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001648 }
1649
Yi Kong26d104a2014-08-13 19:18:14 +00001650 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1651 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1652 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1653 }
1654
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001655 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1656 BuiltinID == ARM::BI__builtin_arm_wsr64)
1657 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1658
1659 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1660 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1661 BuiltinID == ARM::BI__builtin_arm_wsr ||
1662 BuiltinID == ARM::BI__builtin_arm_wsrp)
1663 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1664
Tim Northover12670412014-02-19 10:37:05 +00001665 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1666 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001667
Yi Kong4efadfb2014-07-03 16:01:25 +00001668 // For intrinsics which take an immediate value as part of the instruction,
1669 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001670 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001671 switch (BuiltinID) {
1672 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001673 case ARM::BI__builtin_arm_ssat:
1674 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1675 case ARM::BI__builtin_arm_usat:
1676 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1677 case ARM::BI__builtin_arm_ssat16:
1678 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1679 case ARM::BI__builtin_arm_usat16:
1680 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001681 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001682 case ARM::BI__builtin_arm_vcvtr_d:
1683 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001684 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001685 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001686 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001687 case ARM::BI__builtin_arm_dbg:
1688 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001689 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001690}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001691
Tim Northover573cbee2014-05-24 12:52:07 +00001692bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001693 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001694 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001695 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1696 BuiltinID == AArch64::BI__builtin_arm_strex ||
1697 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001698 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1699 }
1700
Yi Konga5548432014-08-13 19:18:20 +00001701 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1702 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1703 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1704 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1705 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1706 }
1707
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001708 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1709 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001710 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001711
1712 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1713 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1714 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1715 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1716 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1717
Tim Northovera2ee4332014-03-29 15:09:45 +00001718 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1719 return true;
1720
Yi Kong19a29ac2014-07-17 10:52:06 +00001721 // For intrinsics which take an immediate value as part of the instruction,
1722 // range check them here.
1723 unsigned i = 0, l = 0, u = 0;
1724 switch (BuiltinID) {
1725 default: return false;
1726 case AArch64::BI__builtin_arm_dmb:
1727 case AArch64::BI__builtin_arm_dsb:
1728 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1729 }
1730
Yi Kong19a29ac2014-07-17 10:52:06 +00001731 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001732}
1733
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001734bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1735 CallExpr *TheCall) {
1736 struct ArgInfo {
1737 ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1738 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1739 unsigned OpNum = 0;
1740 bool IsSigned = false;
1741 unsigned BitWidth = 0;
1742 unsigned Align = 0;
1743 };
1744
1745 static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1746 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
1747 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
1748 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
1749 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
1750 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
1751 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
1752 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
1753 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
1754 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
1755 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
1756 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
1757
1758 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
1759 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
1760 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
1761 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
1762 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
1763 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
1764 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
1765 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
1766 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
1767 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
1768 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
1769
1770 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
1771 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
1772 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
1773 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
1774 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
1775 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
1776 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
1777 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
1778 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
1779 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
1780 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
1781 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
1782 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
1783 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
1784 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
1785 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
1786 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
1787 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
1788 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
1789 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
1790 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
1791 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
1792 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
1793 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
1794 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
1795 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
1796 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
1797 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
1798 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
1799 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
1800 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
1801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
1802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
1803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
1804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
1805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
1806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
1807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
1808 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
1809 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
1810 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
1811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
1812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
1813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
1814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
1815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
1816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
1817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
1818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
1819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
1820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
1821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1822 {{ 1, false, 6, 0 }} },
1823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
1824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
1825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
1826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
1827 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
1828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
1829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1830 {{ 1, false, 5, 0 }} },
1831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
1832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
1833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
1834 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
1835 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
1836 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
1837 { 2, false, 5, 0 }} },
1838 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
1839 { 2, false, 6, 0 }} },
1840 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
1841 { 3, false, 5, 0 }} },
1842 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
1843 { 3, false, 6, 0 }} },
1844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
1845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
1846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
1847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
1848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
1849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
1850 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
1851 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
1852 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
1853 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
1854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
1855 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
1856 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
1857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
1858 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
1859 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1860 {{ 2, false, 4, 0 },
1861 { 3, false, 5, 0 }} },
1862 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1863 {{ 2, false, 4, 0 },
1864 { 3, false, 5, 0 }} },
1865 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1866 {{ 2, false, 4, 0 },
1867 { 3, false, 5, 0 }} },
1868 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1869 {{ 2, false, 4, 0 },
1870 { 3, false, 5, 0 }} },
1871 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
1872 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
1873 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
1874 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
1875 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
1876 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
1877 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
1878 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
1879 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
1880 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
1881 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
1882 { 2, false, 5, 0 }} },
1883 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
1884 { 2, false, 6, 0 }} },
1885 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
1886 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
1887 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
1888 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
1889 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
1890 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
1891 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
1892 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
1893 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1894 {{ 1, false, 4, 0 }} },
1895 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
1896 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1897 {{ 1, false, 4, 0 }} },
1898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
1899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
1900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
1901 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
1902 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
1903 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
1904 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
1905 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
1906 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
1907 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
1908 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
1909 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
1910 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
1911 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
1912 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
1913 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
1914 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
1915 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
1916 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
1917 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1918 {{ 3, false, 1, 0 }} },
1919 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
1920 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
1921 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
1922 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1923 {{ 3, false, 1, 0 }} },
1924 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
1925 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
1926 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
1927 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1928 {{ 3, false, 1, 0 }} },
1929 };
1930
1931 auto F = Infos.find(BuiltinID);
1932 if (F == Infos.end())
1933 return false;
1934
1935 bool Error = false;
1936
1937 for (const ArgInfo &A : F->second) {
1938 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1939 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1940 if (!A.Align) {
1941 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1942 } else {
1943 unsigned M = 1 << A.Align;
1944 Min *= M;
1945 Max *= M;
1946 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1947 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1948 }
1949 }
1950 return Error;
1951}
1952
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001953// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1954// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1955// ordering for DSP is unspecified. MSA is ordered by the data format used
1956// by the underlying instruction i.e., df/m, df/n and then by size.
1957//
1958// FIXME: The size tests here should instead be tablegen'd along with the
1959// definitions from include/clang/Basic/BuiltinsMips.def.
1960// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1961// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001962bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001963 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001964 switch (BuiltinID) {
1965 default: return false;
1966 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1967 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001968 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1969 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1970 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1971 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1972 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001973 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1974 // df/m field.
1975 // These intrinsics take an unsigned 3 bit immediate.
1976 case Mips::BI__builtin_msa_bclri_b:
1977 case Mips::BI__builtin_msa_bnegi_b:
1978 case Mips::BI__builtin_msa_bseti_b:
1979 case Mips::BI__builtin_msa_sat_s_b:
1980 case Mips::BI__builtin_msa_sat_u_b:
1981 case Mips::BI__builtin_msa_slli_b:
1982 case Mips::BI__builtin_msa_srai_b:
1983 case Mips::BI__builtin_msa_srari_b:
1984 case Mips::BI__builtin_msa_srli_b:
1985 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1986 case Mips::BI__builtin_msa_binsli_b:
1987 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1988 // These intrinsics take an unsigned 4 bit immediate.
1989 case Mips::BI__builtin_msa_bclri_h:
1990 case Mips::BI__builtin_msa_bnegi_h:
1991 case Mips::BI__builtin_msa_bseti_h:
1992 case Mips::BI__builtin_msa_sat_s_h:
1993 case Mips::BI__builtin_msa_sat_u_h:
1994 case Mips::BI__builtin_msa_slli_h:
1995 case Mips::BI__builtin_msa_srai_h:
1996 case Mips::BI__builtin_msa_srari_h:
1997 case Mips::BI__builtin_msa_srli_h:
1998 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1999 case Mips::BI__builtin_msa_binsli_h:
2000 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002001 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002002 // The first block of intrinsics actually have an unsigned 5 bit field,
2003 // not a df/n field.
2004 case Mips::BI__builtin_msa_clei_u_b:
2005 case Mips::BI__builtin_msa_clei_u_h:
2006 case Mips::BI__builtin_msa_clei_u_w:
2007 case Mips::BI__builtin_msa_clei_u_d:
2008 case Mips::BI__builtin_msa_clti_u_b:
2009 case Mips::BI__builtin_msa_clti_u_h:
2010 case Mips::BI__builtin_msa_clti_u_w:
2011 case Mips::BI__builtin_msa_clti_u_d:
2012 case Mips::BI__builtin_msa_maxi_u_b:
2013 case Mips::BI__builtin_msa_maxi_u_h:
2014 case Mips::BI__builtin_msa_maxi_u_w:
2015 case Mips::BI__builtin_msa_maxi_u_d:
2016 case Mips::BI__builtin_msa_mini_u_b:
2017 case Mips::BI__builtin_msa_mini_u_h:
2018 case Mips::BI__builtin_msa_mini_u_w:
2019 case Mips::BI__builtin_msa_mini_u_d:
2020 case Mips::BI__builtin_msa_addvi_b:
2021 case Mips::BI__builtin_msa_addvi_h:
2022 case Mips::BI__builtin_msa_addvi_w:
2023 case Mips::BI__builtin_msa_addvi_d:
2024 case Mips::BI__builtin_msa_bclri_w:
2025 case Mips::BI__builtin_msa_bnegi_w:
2026 case Mips::BI__builtin_msa_bseti_w:
2027 case Mips::BI__builtin_msa_sat_s_w:
2028 case Mips::BI__builtin_msa_sat_u_w:
2029 case Mips::BI__builtin_msa_slli_w:
2030 case Mips::BI__builtin_msa_srai_w:
2031 case Mips::BI__builtin_msa_srari_w:
2032 case Mips::BI__builtin_msa_srli_w:
2033 case Mips::BI__builtin_msa_srlri_w:
2034 case Mips::BI__builtin_msa_subvi_b:
2035 case Mips::BI__builtin_msa_subvi_h:
2036 case Mips::BI__builtin_msa_subvi_w:
2037 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2038 case Mips::BI__builtin_msa_binsli_w:
2039 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2040 // These intrinsics take an unsigned 6 bit immediate.
2041 case Mips::BI__builtin_msa_bclri_d:
2042 case Mips::BI__builtin_msa_bnegi_d:
2043 case Mips::BI__builtin_msa_bseti_d:
2044 case Mips::BI__builtin_msa_sat_s_d:
2045 case Mips::BI__builtin_msa_sat_u_d:
2046 case Mips::BI__builtin_msa_slli_d:
2047 case Mips::BI__builtin_msa_srai_d:
2048 case Mips::BI__builtin_msa_srari_d:
2049 case Mips::BI__builtin_msa_srli_d:
2050 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2051 case Mips::BI__builtin_msa_binsli_d:
2052 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2053 // These intrinsics take a signed 5 bit immediate.
2054 case Mips::BI__builtin_msa_ceqi_b:
2055 case Mips::BI__builtin_msa_ceqi_h:
2056 case Mips::BI__builtin_msa_ceqi_w:
2057 case Mips::BI__builtin_msa_ceqi_d:
2058 case Mips::BI__builtin_msa_clti_s_b:
2059 case Mips::BI__builtin_msa_clti_s_h:
2060 case Mips::BI__builtin_msa_clti_s_w:
2061 case Mips::BI__builtin_msa_clti_s_d:
2062 case Mips::BI__builtin_msa_clei_s_b:
2063 case Mips::BI__builtin_msa_clei_s_h:
2064 case Mips::BI__builtin_msa_clei_s_w:
2065 case Mips::BI__builtin_msa_clei_s_d:
2066 case Mips::BI__builtin_msa_maxi_s_b:
2067 case Mips::BI__builtin_msa_maxi_s_h:
2068 case Mips::BI__builtin_msa_maxi_s_w:
2069 case Mips::BI__builtin_msa_maxi_s_d:
2070 case Mips::BI__builtin_msa_mini_s_b:
2071 case Mips::BI__builtin_msa_mini_s_h:
2072 case Mips::BI__builtin_msa_mini_s_w:
2073 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2074 // These intrinsics take an unsigned 8 bit immediate.
2075 case Mips::BI__builtin_msa_andi_b:
2076 case Mips::BI__builtin_msa_nori_b:
2077 case Mips::BI__builtin_msa_ori_b:
2078 case Mips::BI__builtin_msa_shf_b:
2079 case Mips::BI__builtin_msa_shf_h:
2080 case Mips::BI__builtin_msa_shf_w:
2081 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2082 case Mips::BI__builtin_msa_bseli_b:
2083 case Mips::BI__builtin_msa_bmnzi_b:
2084 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2085 // df/n format
2086 // These intrinsics take an unsigned 4 bit immediate.
2087 case Mips::BI__builtin_msa_copy_s_b:
2088 case Mips::BI__builtin_msa_copy_u_b:
2089 case Mips::BI__builtin_msa_insve_b:
2090 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002091 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2092 // These intrinsics take an unsigned 3 bit immediate.
2093 case Mips::BI__builtin_msa_copy_s_h:
2094 case Mips::BI__builtin_msa_copy_u_h:
2095 case Mips::BI__builtin_msa_insve_h:
2096 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002097 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2098 // These intrinsics take an unsigned 2 bit immediate.
2099 case Mips::BI__builtin_msa_copy_s_w:
2100 case Mips::BI__builtin_msa_copy_u_w:
2101 case Mips::BI__builtin_msa_insve_w:
2102 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002103 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2104 // These intrinsics take an unsigned 1 bit immediate.
2105 case Mips::BI__builtin_msa_copy_s_d:
2106 case Mips::BI__builtin_msa_copy_u_d:
2107 case Mips::BI__builtin_msa_insve_d:
2108 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002109 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2110 // Memory offsets and immediate loads.
2111 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00002112 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002113 case Mips::BI__builtin_msa_ldi_h:
2114 case Mips::BI__builtin_msa_ldi_w:
2115 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2116 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2117 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2118 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2119 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2120 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2121 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2122 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2123 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00002124 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002125
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002126 if (!m)
2127 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2128
2129 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2130 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002131}
2132
Kit Bartone50adcb2015-03-30 19:40:59 +00002133bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2134 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00002135 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2136 BuiltinID == PPC::BI__builtin_divdeu ||
2137 BuiltinID == PPC::BI__builtin_bpermd;
2138 bool IsTarget64Bit = Context.getTargetInfo()
2139 .getTypeWidth(Context
2140 .getTargetInfo()
2141 .getIntPtrType()) == 64;
2142 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2143 BuiltinID == PPC::BI__builtin_divweu ||
2144 BuiltinID == PPC::BI__builtin_divde ||
2145 BuiltinID == PPC::BI__builtin_divdeu;
2146
2147 if (Is64BitBltin && !IsTarget64Bit)
2148 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2149 << TheCall->getSourceRange();
2150
2151 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2152 (BuiltinID == PPC::BI__builtin_bpermd &&
2153 !Context.getTargetInfo().hasFeature("bpermd")))
2154 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2155 << TheCall->getSourceRange();
2156
Kit Bartone50adcb2015-03-30 19:40:59 +00002157 switch (BuiltinID) {
2158 default: return false;
2159 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2160 case PPC::BI__builtin_altivec_crypto_vshasigmad:
2161 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2162 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2163 case PPC::BI__builtin_tbegin:
2164 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2165 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2166 case PPC::BI__builtin_tabortwc:
2167 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2168 case PPC::BI__builtin_tabortwci:
2169 case PPC::BI__builtin_tabortdci:
2170 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2171 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00002172 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00002173 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00002174 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00002175 }
2176 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2177}
2178
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002179bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2180 CallExpr *TheCall) {
2181 if (BuiltinID == SystemZ::BI__builtin_tabort) {
2182 Expr *Arg = TheCall->getArg(0);
2183 llvm::APSInt AbortCode(32);
2184 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2185 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2186 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2187 << Arg->getSourceRange();
2188 }
2189
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002190 // For intrinsics which take an immediate value as part of the instruction,
2191 // range check them here.
2192 unsigned i = 0, l = 0, u = 0;
2193 switch (BuiltinID) {
2194 default: return false;
2195 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2196 case SystemZ::BI__builtin_s390_verimb:
2197 case SystemZ::BI__builtin_s390_verimh:
2198 case SystemZ::BI__builtin_s390_verimf:
2199 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2200 case SystemZ::BI__builtin_s390_vfaeb:
2201 case SystemZ::BI__builtin_s390_vfaeh:
2202 case SystemZ::BI__builtin_s390_vfaef:
2203 case SystemZ::BI__builtin_s390_vfaebs:
2204 case SystemZ::BI__builtin_s390_vfaehs:
2205 case SystemZ::BI__builtin_s390_vfaefs:
2206 case SystemZ::BI__builtin_s390_vfaezb:
2207 case SystemZ::BI__builtin_s390_vfaezh:
2208 case SystemZ::BI__builtin_s390_vfaezf:
2209 case SystemZ::BI__builtin_s390_vfaezbs:
2210 case SystemZ::BI__builtin_s390_vfaezhs:
2211 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002212 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002213 case SystemZ::BI__builtin_s390_vfidb:
2214 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2215 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002216 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002217 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2218 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2219 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2220 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2221 case SystemZ::BI__builtin_s390_vstrcb:
2222 case SystemZ::BI__builtin_s390_vstrch:
2223 case SystemZ::BI__builtin_s390_vstrcf:
2224 case SystemZ::BI__builtin_s390_vstrczb:
2225 case SystemZ::BI__builtin_s390_vstrczh:
2226 case SystemZ::BI__builtin_s390_vstrczf:
2227 case SystemZ::BI__builtin_s390_vstrcbs:
2228 case SystemZ::BI__builtin_s390_vstrchs:
2229 case SystemZ::BI__builtin_s390_vstrcfs:
2230 case SystemZ::BI__builtin_s390_vstrczbs:
2231 case SystemZ::BI__builtin_s390_vstrczhs:
2232 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002233 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2234 case SystemZ::BI__builtin_s390_vfminsb:
2235 case SystemZ::BI__builtin_s390_vfmaxsb:
2236 case SystemZ::BI__builtin_s390_vfmindb:
2237 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002238 }
2239 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002240}
2241
Craig Topper5ba2c502015-11-07 08:08:31 +00002242/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2243/// This checks that the target supports __builtin_cpu_supports and
2244/// that the string argument is constant and valid.
2245static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2246 Expr *Arg = TheCall->getArg(0);
2247
2248 // Check if the argument is a string literal.
2249 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2250 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2251 << Arg->getSourceRange();
2252
2253 // Check the contents of the string.
2254 StringRef Feature =
2255 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2256 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2257 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2258 << Arg->getSourceRange();
2259 return false;
2260}
2261
Craig Topper699ae0c2017-08-10 20:28:30 +00002262/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2263/// This checks that the target supports __builtin_cpu_is and
2264/// that the string argument is constant and valid.
2265static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2266 Expr *Arg = TheCall->getArg(0);
2267
2268 // Check if the argument is a string literal.
2269 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2270 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2271 << Arg->getSourceRange();
2272
2273 // Check the contents of the string.
2274 StringRef Feature =
2275 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2276 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2277 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2278 << Arg->getSourceRange();
2279 return false;
2280}
2281
Craig Toppera7e253e2016-09-23 04:48:31 +00002282// Check if the rounding mode is legal.
2283bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2284 // Indicates if this instruction has rounding control or just SAE.
2285 bool HasRC = false;
2286
2287 unsigned ArgNum = 0;
2288 switch (BuiltinID) {
2289 default:
2290 return false;
2291 case X86::BI__builtin_ia32_vcvttsd2si32:
2292 case X86::BI__builtin_ia32_vcvttsd2si64:
2293 case X86::BI__builtin_ia32_vcvttsd2usi32:
2294 case X86::BI__builtin_ia32_vcvttsd2usi64:
2295 case X86::BI__builtin_ia32_vcvttss2si32:
2296 case X86::BI__builtin_ia32_vcvttss2si64:
2297 case X86::BI__builtin_ia32_vcvttss2usi32:
2298 case X86::BI__builtin_ia32_vcvttss2usi64:
2299 ArgNum = 1;
2300 break;
2301 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2302 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2303 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2304 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2305 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2306 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2307 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2308 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2309 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2310 case X86::BI__builtin_ia32_exp2pd_mask:
2311 case X86::BI__builtin_ia32_exp2ps_mask:
2312 case X86::BI__builtin_ia32_getexppd512_mask:
2313 case X86::BI__builtin_ia32_getexpps512_mask:
2314 case X86::BI__builtin_ia32_rcp28pd_mask:
2315 case X86::BI__builtin_ia32_rcp28ps_mask:
2316 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2317 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2318 case X86::BI__builtin_ia32_vcomisd:
2319 case X86::BI__builtin_ia32_vcomiss:
2320 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2321 ArgNum = 3;
2322 break;
2323 case X86::BI__builtin_ia32_cmppd512_mask:
2324 case X86::BI__builtin_ia32_cmpps512_mask:
2325 case X86::BI__builtin_ia32_cmpsd_mask:
2326 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002327 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002328 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2329 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002330 case X86::BI__builtin_ia32_maxpd512_mask:
2331 case X86::BI__builtin_ia32_maxps512_mask:
2332 case X86::BI__builtin_ia32_maxsd_round_mask:
2333 case X86::BI__builtin_ia32_maxss_round_mask:
2334 case X86::BI__builtin_ia32_minpd512_mask:
2335 case X86::BI__builtin_ia32_minps512_mask:
2336 case X86::BI__builtin_ia32_minsd_round_mask:
2337 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002338 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2339 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2340 case X86::BI__builtin_ia32_reducepd512_mask:
2341 case X86::BI__builtin_ia32_reduceps512_mask:
2342 case X86::BI__builtin_ia32_rndscalepd_mask:
2343 case X86::BI__builtin_ia32_rndscaleps_mask:
2344 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2345 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2346 ArgNum = 4;
2347 break;
2348 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002349 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002350 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002351 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002352 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002353 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002354 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002355 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002356 case X86::BI__builtin_ia32_rangepd512_mask:
2357 case X86::BI__builtin_ia32_rangeps512_mask:
2358 case X86::BI__builtin_ia32_rangesd128_round_mask:
2359 case X86::BI__builtin_ia32_rangess128_round_mask:
2360 case X86::BI__builtin_ia32_reducesd_mask:
2361 case X86::BI__builtin_ia32_reducess_mask:
2362 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2363 case X86::BI__builtin_ia32_rndscaless_round_mask:
2364 ArgNum = 5;
2365 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002366 case X86::BI__builtin_ia32_vcvtsd2si64:
2367 case X86::BI__builtin_ia32_vcvtsd2si32:
2368 case X86::BI__builtin_ia32_vcvtsd2usi32:
2369 case X86::BI__builtin_ia32_vcvtsd2usi64:
2370 case X86::BI__builtin_ia32_vcvtss2si32:
2371 case X86::BI__builtin_ia32_vcvtss2si64:
2372 case X86::BI__builtin_ia32_vcvtss2usi32:
2373 case X86::BI__builtin_ia32_vcvtss2usi64:
2374 ArgNum = 1;
2375 HasRC = true;
2376 break;
Craig Topper3614b412018-06-10 06:01:42 +00002377 case X86::BI__builtin_ia32_addpd512:
2378 case X86::BI__builtin_ia32_addps512:
2379 case X86::BI__builtin_ia32_divpd512:
2380 case X86::BI__builtin_ia32_divps512:
2381 case X86::BI__builtin_ia32_mulpd512:
2382 case X86::BI__builtin_ia32_mulps512:
2383 case X86::BI__builtin_ia32_subpd512:
2384 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00002385 case X86::BI__builtin_ia32_cvtsi2sd64:
2386 case X86::BI__builtin_ia32_cvtsi2ss32:
2387 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002388 case X86::BI__builtin_ia32_cvtusi2sd64:
2389 case X86::BI__builtin_ia32_cvtusi2ss32:
2390 case X86::BI__builtin_ia32_cvtusi2ss64:
2391 ArgNum = 2;
2392 HasRC = true;
2393 break;
2394 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2395 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2396 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2397 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2398 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2399 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2400 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2401 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2402 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2403 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2404 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002405 case X86::BI__builtin_ia32_sqrtpd512_mask:
2406 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002407 ArgNum = 3;
2408 HasRC = true;
2409 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002410 case X86::BI__builtin_ia32_addss_round_mask:
2411 case X86::BI__builtin_ia32_addsd_round_mask:
2412 case X86::BI__builtin_ia32_divss_round_mask:
2413 case X86::BI__builtin_ia32_divsd_round_mask:
2414 case X86::BI__builtin_ia32_mulss_round_mask:
2415 case X86::BI__builtin_ia32_mulsd_round_mask:
2416 case X86::BI__builtin_ia32_subss_round_mask:
2417 case X86::BI__builtin_ia32_subsd_round_mask:
2418 case X86::BI__builtin_ia32_scalefpd512_mask:
2419 case X86::BI__builtin_ia32_scalefps512_mask:
2420 case X86::BI__builtin_ia32_scalefsd_round_mask:
2421 case X86::BI__builtin_ia32_scalefss_round_mask:
2422 case X86::BI__builtin_ia32_getmantpd512_mask:
2423 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002424 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2425 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2426 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002427 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2428 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2429 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2430 case X86::BI__builtin_ia32_vfmaddss3_mask:
2431 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2432 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00002433 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2434 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2435 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2436 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2437 case X86::BI__builtin_ia32_vfmaddps512_mask:
2438 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2439 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2440 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2441 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2442 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2443 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2444 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2445 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2446 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2447 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2448 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00002449 ArgNum = 4;
2450 HasRC = true;
2451 break;
2452 case X86::BI__builtin_ia32_getmantsd_round_mask:
2453 case X86::BI__builtin_ia32_getmantss_round_mask:
2454 ArgNum = 5;
2455 HasRC = true;
2456 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002457 }
2458
2459 llvm::APSInt Result;
2460
2461 // We can't check the value of a dependent argument.
2462 Expr *Arg = TheCall->getArg(ArgNum);
2463 if (Arg->isTypeDependent() || Arg->isValueDependent())
2464 return false;
2465
2466 // Check constant-ness first.
2467 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2468 return true;
2469
2470 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2471 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2472 // combined with ROUND_NO_EXC.
2473 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2474 Result == 8/*ROUND_NO_EXC*/ ||
2475 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2476 return false;
2477
2478 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2479 << Arg->getSourceRange();
2480}
2481
Craig Topperdf5beb22017-03-13 17:16:50 +00002482// Check if the gather/scatter scale is legal.
2483bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2484 CallExpr *TheCall) {
2485 unsigned ArgNum = 0;
2486 switch (BuiltinID) {
2487 default:
2488 return false;
2489 case X86::BI__builtin_ia32_gatherpfdpd:
2490 case X86::BI__builtin_ia32_gatherpfdps:
2491 case X86::BI__builtin_ia32_gatherpfqpd:
2492 case X86::BI__builtin_ia32_gatherpfqps:
2493 case X86::BI__builtin_ia32_scatterpfdpd:
2494 case X86::BI__builtin_ia32_scatterpfdps:
2495 case X86::BI__builtin_ia32_scatterpfqpd:
2496 case X86::BI__builtin_ia32_scatterpfqps:
2497 ArgNum = 3;
2498 break;
2499 case X86::BI__builtin_ia32_gatherd_pd:
2500 case X86::BI__builtin_ia32_gatherd_pd256:
2501 case X86::BI__builtin_ia32_gatherq_pd:
2502 case X86::BI__builtin_ia32_gatherq_pd256:
2503 case X86::BI__builtin_ia32_gatherd_ps:
2504 case X86::BI__builtin_ia32_gatherd_ps256:
2505 case X86::BI__builtin_ia32_gatherq_ps:
2506 case X86::BI__builtin_ia32_gatherq_ps256:
2507 case X86::BI__builtin_ia32_gatherd_q:
2508 case X86::BI__builtin_ia32_gatherd_q256:
2509 case X86::BI__builtin_ia32_gatherq_q:
2510 case X86::BI__builtin_ia32_gatherq_q256:
2511 case X86::BI__builtin_ia32_gatherd_d:
2512 case X86::BI__builtin_ia32_gatherd_d256:
2513 case X86::BI__builtin_ia32_gatherq_d:
2514 case X86::BI__builtin_ia32_gatherq_d256:
2515 case X86::BI__builtin_ia32_gather3div2df:
2516 case X86::BI__builtin_ia32_gather3div2di:
2517 case X86::BI__builtin_ia32_gather3div4df:
2518 case X86::BI__builtin_ia32_gather3div4di:
2519 case X86::BI__builtin_ia32_gather3div4sf:
2520 case X86::BI__builtin_ia32_gather3div4si:
2521 case X86::BI__builtin_ia32_gather3div8sf:
2522 case X86::BI__builtin_ia32_gather3div8si:
2523 case X86::BI__builtin_ia32_gather3siv2df:
2524 case X86::BI__builtin_ia32_gather3siv2di:
2525 case X86::BI__builtin_ia32_gather3siv4df:
2526 case X86::BI__builtin_ia32_gather3siv4di:
2527 case X86::BI__builtin_ia32_gather3siv4sf:
2528 case X86::BI__builtin_ia32_gather3siv4si:
2529 case X86::BI__builtin_ia32_gather3siv8sf:
2530 case X86::BI__builtin_ia32_gather3siv8si:
2531 case X86::BI__builtin_ia32_gathersiv8df:
2532 case X86::BI__builtin_ia32_gathersiv16sf:
2533 case X86::BI__builtin_ia32_gatherdiv8df:
2534 case X86::BI__builtin_ia32_gatherdiv16sf:
2535 case X86::BI__builtin_ia32_gathersiv8di:
2536 case X86::BI__builtin_ia32_gathersiv16si:
2537 case X86::BI__builtin_ia32_gatherdiv8di:
2538 case X86::BI__builtin_ia32_gatherdiv16si:
2539 case X86::BI__builtin_ia32_scatterdiv2df:
2540 case X86::BI__builtin_ia32_scatterdiv2di:
2541 case X86::BI__builtin_ia32_scatterdiv4df:
2542 case X86::BI__builtin_ia32_scatterdiv4di:
2543 case X86::BI__builtin_ia32_scatterdiv4sf:
2544 case X86::BI__builtin_ia32_scatterdiv4si:
2545 case X86::BI__builtin_ia32_scatterdiv8sf:
2546 case X86::BI__builtin_ia32_scatterdiv8si:
2547 case X86::BI__builtin_ia32_scattersiv2df:
2548 case X86::BI__builtin_ia32_scattersiv2di:
2549 case X86::BI__builtin_ia32_scattersiv4df:
2550 case X86::BI__builtin_ia32_scattersiv4di:
2551 case X86::BI__builtin_ia32_scattersiv4sf:
2552 case X86::BI__builtin_ia32_scattersiv4si:
2553 case X86::BI__builtin_ia32_scattersiv8sf:
2554 case X86::BI__builtin_ia32_scattersiv8si:
2555 case X86::BI__builtin_ia32_scattersiv8df:
2556 case X86::BI__builtin_ia32_scattersiv16sf:
2557 case X86::BI__builtin_ia32_scatterdiv8df:
2558 case X86::BI__builtin_ia32_scatterdiv16sf:
2559 case X86::BI__builtin_ia32_scattersiv8di:
2560 case X86::BI__builtin_ia32_scattersiv16si:
2561 case X86::BI__builtin_ia32_scatterdiv8di:
2562 case X86::BI__builtin_ia32_scatterdiv16si:
2563 ArgNum = 4;
2564 break;
2565 }
2566
2567 llvm::APSInt Result;
2568
2569 // We can't check the value of a dependent argument.
2570 Expr *Arg = TheCall->getArg(ArgNum);
2571 if (Arg->isTypeDependent() || Arg->isValueDependent())
2572 return false;
2573
2574 // Check constant-ness first.
2575 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2576 return true;
2577
2578 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2579 return false;
2580
2581 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2582 << Arg->getSourceRange();
2583}
2584
Craig Topper51738f82018-04-26 20:14:46 +00002585static bool isX86_32Builtin(unsigned BuiltinID) {
2586 // These builtins only work on x86-32 targets.
2587 switch (BuiltinID) {
2588 case X86::BI__builtin_ia32_readeflags_u32:
2589 case X86::BI__builtin_ia32_writeeflags_u32:
2590 return true;
2591 }
2592
2593 return false;
2594}
2595
Craig Topperf0ddc892016-09-23 04:48:27 +00002596bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2597 if (BuiltinID == X86::BI__builtin_cpu_supports)
2598 return SemaBuiltinCpuSupports(*this, TheCall);
2599
Craig Topper699ae0c2017-08-10 20:28:30 +00002600 if (BuiltinID == X86::BI__builtin_cpu_is)
2601 return SemaBuiltinCpuIs(*this, TheCall);
2602
Craig Topper51738f82018-04-26 20:14:46 +00002603 // Check for 32-bit only builtins on a 64-bit target.
2604 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2605 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2606 return Diag(TheCall->getCallee()->getLocStart(),
2607 diag::err_32_bit_builtin_64_bit_tgt);
2608
Craig Toppera7e253e2016-09-23 04:48:31 +00002609 // If the intrinsic has rounding or SAE make sure its valid.
2610 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2611 return true;
2612
Craig Topperdf5beb22017-03-13 17:16:50 +00002613 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2614 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2615 return true;
2616
Craig Topperf0ddc892016-09-23 04:48:27 +00002617 // For intrinsics which take an immediate value as part of the instruction,
2618 // range check them here.
2619 int i = 0, l = 0, u = 0;
2620 switch (BuiltinID) {
2621 default:
2622 return false;
Craig Topper11899b02018-06-05 21:54:35 +00002623 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00002624 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002625 case X86::BI__builtin_ia32_vextractf128_pd256:
2626 case X86::BI__builtin_ia32_vextractf128_ps256:
2627 case X86::BI__builtin_ia32_vextractf128_si256:
2628 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00002629 case X86::BI__builtin_ia32_extractf64x4_mask:
2630 case X86::BI__builtin_ia32_extracti64x4_mask:
2631 case X86::BI__builtin_ia32_extractf32x8_mask:
2632 case X86::BI__builtin_ia32_extracti32x8_mask:
2633 case X86::BI__builtin_ia32_extractf64x2_256_mask:
2634 case X86::BI__builtin_ia32_extracti64x2_256_mask:
2635 case X86::BI__builtin_ia32_extractf32x4_256_mask:
2636 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002637 i = 1; l = 0; u = 1;
2638 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002639 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002640 case X86::BI__builtin_ia32_vinsertf128_pd256:
2641 case X86::BI__builtin_ia32_vinsertf128_ps256:
2642 case X86::BI__builtin_ia32_vinsertf128_si256:
2643 case X86::BI__builtin_ia32_insert128i256:
2644 case X86::BI__builtin_ia32_insertf32x8:
2645 case X86::BI__builtin_ia32_inserti32x8:
2646 case X86::BI__builtin_ia32_insertf64x4:
2647 case X86::BI__builtin_ia32_inserti64x4:
2648 case X86::BI__builtin_ia32_insertf64x2_256:
2649 case X86::BI__builtin_ia32_inserti64x2_256:
2650 case X86::BI__builtin_ia32_insertf32x4_256:
2651 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00002652 i = 2; l = 0; u = 1;
2653 break;
Craig Topperacf56012018-06-08 00:59:27 +00002654 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00002655 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002656 case X86::BI__builtin_ia32_vec_ext_v4si:
2657 case X86::BI__builtin_ia32_vec_ext_v4sf:
2658 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00002659 case X86::BI__builtin_ia32_extractf32x4_mask:
2660 case X86::BI__builtin_ia32_extracti32x4_mask:
2661 case X86::BI__builtin_ia32_extractf64x2_512_mask:
2662 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002663 i = 1; l = 0; u = 3;
2664 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002665 case X86::BI_mm_prefetch:
2666 case X86::BI__builtin_ia32_vec_ext_v8hi:
2667 case X86::BI__builtin_ia32_vec_ext_v8si:
2668 i = 1; l = 0; u = 7;
2669 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002670 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00002671 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00002672 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00002673 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002674 case X86::BI__builtin_ia32_vec_set_v4si:
2675 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00002676 case X86::BI__builtin_ia32_shuf_f32x4_256:
2677 case X86::BI__builtin_ia32_shuf_f64x2_256:
2678 case X86::BI__builtin_ia32_shuf_i32x4_256:
2679 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00002680 case X86::BI__builtin_ia32_insertf64x2_512:
2681 case X86::BI__builtin_ia32_inserti64x2_512:
2682 case X86::BI__builtin_ia32_insertf32x4:
2683 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00002684 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002685 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002686 case X86::BI__builtin_ia32_vpermil2pd:
2687 case X86::BI__builtin_ia32_vpermil2pd256:
2688 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002689 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002690 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002691 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002692 case X86::BI__builtin_ia32_cmpb128_mask:
2693 case X86::BI__builtin_ia32_cmpw128_mask:
2694 case X86::BI__builtin_ia32_cmpd128_mask:
2695 case X86::BI__builtin_ia32_cmpq128_mask:
2696 case X86::BI__builtin_ia32_cmpb256_mask:
2697 case X86::BI__builtin_ia32_cmpw256_mask:
2698 case X86::BI__builtin_ia32_cmpd256_mask:
2699 case X86::BI__builtin_ia32_cmpq256_mask:
2700 case X86::BI__builtin_ia32_cmpb512_mask:
2701 case X86::BI__builtin_ia32_cmpw512_mask:
2702 case X86::BI__builtin_ia32_cmpd512_mask:
2703 case X86::BI__builtin_ia32_cmpq512_mask:
2704 case X86::BI__builtin_ia32_ucmpb128_mask:
2705 case X86::BI__builtin_ia32_ucmpw128_mask:
2706 case X86::BI__builtin_ia32_ucmpd128_mask:
2707 case X86::BI__builtin_ia32_ucmpq128_mask:
2708 case X86::BI__builtin_ia32_ucmpb256_mask:
2709 case X86::BI__builtin_ia32_ucmpw256_mask:
2710 case X86::BI__builtin_ia32_ucmpd256_mask:
2711 case X86::BI__builtin_ia32_ucmpq256_mask:
2712 case X86::BI__builtin_ia32_ucmpb512_mask:
2713 case X86::BI__builtin_ia32_ucmpw512_mask:
2714 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002715 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002716 case X86::BI__builtin_ia32_vpcomub:
2717 case X86::BI__builtin_ia32_vpcomuw:
2718 case X86::BI__builtin_ia32_vpcomud:
2719 case X86::BI__builtin_ia32_vpcomuq:
2720 case X86::BI__builtin_ia32_vpcomb:
2721 case X86::BI__builtin_ia32_vpcomw:
2722 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002723 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002724 case X86::BI__builtin_ia32_vec_set_v8hi:
2725 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002726 i = 2; l = 0; u = 7;
2727 break;
Craig Topperacf56012018-06-08 00:59:27 +00002728 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002729 case X86::BI__builtin_ia32_roundps:
2730 case X86::BI__builtin_ia32_roundpd:
2731 case X86::BI__builtin_ia32_roundps256:
2732 case X86::BI__builtin_ia32_roundpd256:
Craig Topper03a1d482018-06-15 17:03:32 +00002733 case X86::BI__builtin_ia32_getmantpd128_mask:
2734 case X86::BI__builtin_ia32_getmantpd256_mask:
2735 case X86::BI__builtin_ia32_getmantps128_mask:
2736 case X86::BI__builtin_ia32_getmantps256_mask:
2737 case X86::BI__builtin_ia32_getmantpd512_mask:
2738 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002739 case X86::BI__builtin_ia32_vec_ext_v16qi:
2740 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002741 i = 1; l = 0; u = 15;
2742 break;
Craig Topper7d17d722018-06-08 00:00:21 +00002743 case X86::BI__builtin_ia32_pblendd128:
2744 case X86::BI__builtin_ia32_blendps:
2745 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00002746 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002747 case X86::BI__builtin_ia32_roundss:
2748 case X86::BI__builtin_ia32_roundsd:
2749 case X86::BI__builtin_ia32_rangepd128_mask:
2750 case X86::BI__builtin_ia32_rangepd256_mask:
2751 case X86::BI__builtin_ia32_rangepd512_mask:
2752 case X86::BI__builtin_ia32_rangeps128_mask:
2753 case X86::BI__builtin_ia32_rangeps256_mask:
2754 case X86::BI__builtin_ia32_rangeps512_mask:
2755 case X86::BI__builtin_ia32_getmantsd_round_mask:
2756 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002757 case X86::BI__builtin_ia32_vec_set_v16qi:
2758 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002759 i = 2; l = 0; u = 15;
2760 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002761 case X86::BI__builtin_ia32_vec_ext_v32qi:
2762 i = 1; l = 0; u = 31;
2763 break;
Craig Topper39c87102016-05-18 03:18:12 +00002764 case X86::BI__builtin_ia32_cmpps:
2765 case X86::BI__builtin_ia32_cmpss:
2766 case X86::BI__builtin_ia32_cmppd:
2767 case X86::BI__builtin_ia32_cmpsd:
2768 case X86::BI__builtin_ia32_cmpps256:
2769 case X86::BI__builtin_ia32_cmppd256:
2770 case X86::BI__builtin_ia32_cmpps128_mask:
2771 case X86::BI__builtin_ia32_cmppd128_mask:
2772 case X86::BI__builtin_ia32_cmpps256_mask:
2773 case X86::BI__builtin_ia32_cmppd256_mask:
2774 case X86::BI__builtin_ia32_cmpps512_mask:
2775 case X86::BI__builtin_ia32_cmppd512_mask:
2776 case X86::BI__builtin_ia32_cmpsd_mask:
2777 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002778 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002779 i = 2; l = 0; u = 31;
2780 break;
Craig Topper03f4f042018-06-08 18:00:25 +00002781 case X86::BI__builtin_ia32_permdf256:
2782 case X86::BI__builtin_ia32_permdi256:
2783 case X86::BI__builtin_ia32_permdf512:
2784 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00002785 case X86::BI__builtin_ia32_vpermilps:
2786 case X86::BI__builtin_ia32_vpermilps256:
2787 case X86::BI__builtin_ia32_vpermilpd512:
2788 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00002789 case X86::BI__builtin_ia32_pshufd:
2790 case X86::BI__builtin_ia32_pshufd256:
2791 case X86::BI__builtin_ia32_pshufd512:
2792 case X86::BI__builtin_ia32_pshufhw:
2793 case X86::BI__builtin_ia32_pshufhw256:
2794 case X86::BI__builtin_ia32_pshufhw512:
2795 case X86::BI__builtin_ia32_pshuflw:
2796 case X86::BI__builtin_ia32_pshuflw256:
2797 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00002798 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002799 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002800 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002801 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2802 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002803 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2804 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2805 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2806 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2807 case X86::BI__builtin_ia32_rndscaleps_mask:
2808 case X86::BI__builtin_ia32_rndscalepd_mask:
2809 case X86::BI__builtin_ia32_reducepd128_mask:
2810 case X86::BI__builtin_ia32_reducepd256_mask:
2811 case X86::BI__builtin_ia32_reducepd512_mask:
2812 case X86::BI__builtin_ia32_reduceps128_mask:
2813 case X86::BI__builtin_ia32_reduceps256_mask:
2814 case X86::BI__builtin_ia32_reduceps512_mask:
2815 case X86::BI__builtin_ia32_prold512_mask:
2816 case X86::BI__builtin_ia32_prolq512_mask:
2817 case X86::BI__builtin_ia32_prold128_mask:
2818 case X86::BI__builtin_ia32_prold256_mask:
2819 case X86::BI__builtin_ia32_prolq128_mask:
2820 case X86::BI__builtin_ia32_prolq256_mask:
Craig Topper4217d172018-06-15 17:40:37 +00002821 case X86::BI__builtin_ia32_prord512_mask:
2822 case X86::BI__builtin_ia32_prorq512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002823 case X86::BI__builtin_ia32_prord128_mask:
2824 case X86::BI__builtin_ia32_prord256_mask:
2825 case X86::BI__builtin_ia32_prorq128_mask:
2826 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002827 case X86::BI__builtin_ia32_fpclasspd128_mask:
2828 case X86::BI__builtin_ia32_fpclasspd256_mask:
2829 case X86::BI__builtin_ia32_fpclassps128_mask:
2830 case X86::BI__builtin_ia32_fpclassps256_mask:
2831 case X86::BI__builtin_ia32_fpclassps512_mask:
2832 case X86::BI__builtin_ia32_fpclasspd512_mask:
2833 case X86::BI__builtin_ia32_fpclasssd_mask:
2834 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00002835 case X86::BI__builtin_ia32_pslldqi128_byteshift:
2836 case X86::BI__builtin_ia32_pslldqi256_byteshift:
2837 case X86::BI__builtin_ia32_pslldqi512_byteshift:
2838 case X86::BI__builtin_ia32_psrldqi128_byteshift:
2839 case X86::BI__builtin_ia32_psrldqi256_byteshift:
2840 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper39c87102016-05-18 03:18:12 +00002841 i = 1; l = 0; u = 255;
2842 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00002843 case X86::BI__builtin_ia32_vperm2f128_pd256:
2844 case X86::BI__builtin_ia32_vperm2f128_ps256:
2845 case X86::BI__builtin_ia32_vperm2f128_si256:
2846 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00002847 case X86::BI__builtin_ia32_pblendw128:
2848 case X86::BI__builtin_ia32_pblendw256:
2849 case X86::BI__builtin_ia32_blendps256:
2850 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00002851 case X86::BI__builtin_ia32_palignr128:
2852 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002853 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00002854 case X86::BI__builtin_ia32_alignq512:
2855 case X86::BI__builtin_ia32_alignd512:
2856 case X86::BI__builtin_ia32_alignd128:
2857 case X86::BI__builtin_ia32_alignd256:
2858 case X86::BI__builtin_ia32_alignq128:
2859 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00002860 case X86::BI__builtin_ia32_vcomisd:
2861 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00002862 case X86::BI__builtin_ia32_shuf_f32x4:
2863 case X86::BI__builtin_ia32_shuf_f64x2:
2864 case X86::BI__builtin_ia32_shuf_i32x4:
2865 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00002866 case X86::BI__builtin_ia32_shufpd512:
2867 case X86::BI__builtin_ia32_shufps:
2868 case X86::BI__builtin_ia32_shufps256:
2869 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00002870 case X86::BI__builtin_ia32_dbpsadbw128:
2871 case X86::BI__builtin_ia32_dbpsadbw256:
2872 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00002873 case X86::BI__builtin_ia32_vpshldd128:
2874 case X86::BI__builtin_ia32_vpshldd256:
2875 case X86::BI__builtin_ia32_vpshldd512:
2876 case X86::BI__builtin_ia32_vpshldq128:
2877 case X86::BI__builtin_ia32_vpshldq256:
2878 case X86::BI__builtin_ia32_vpshldq512:
2879 case X86::BI__builtin_ia32_vpshldw128:
2880 case X86::BI__builtin_ia32_vpshldw256:
2881 case X86::BI__builtin_ia32_vpshldw512:
2882 case X86::BI__builtin_ia32_vpshrdd128:
2883 case X86::BI__builtin_ia32_vpshrdd256:
2884 case X86::BI__builtin_ia32_vpshrdd512:
2885 case X86::BI__builtin_ia32_vpshrdq128:
2886 case X86::BI__builtin_ia32_vpshrdq256:
2887 case X86::BI__builtin_ia32_vpshrdq512:
2888 case X86::BI__builtin_ia32_vpshrdw128:
2889 case X86::BI__builtin_ia32_vpshrdw256:
2890 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00002891 i = 2; l = 0; u = 255;
2892 break;
2893 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2894 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2895 case X86::BI__builtin_ia32_fixupimmps512_mask:
2896 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2897 case X86::BI__builtin_ia32_fixupimmsd_mask:
2898 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2899 case X86::BI__builtin_ia32_fixupimmss_mask:
2900 case X86::BI__builtin_ia32_fixupimmss_maskz:
2901 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2902 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2903 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2904 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2905 case X86::BI__builtin_ia32_fixupimmps128_mask:
2906 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2907 case X86::BI__builtin_ia32_fixupimmps256_mask:
2908 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2909 case X86::BI__builtin_ia32_pternlogd512_mask:
2910 case X86::BI__builtin_ia32_pternlogd512_maskz:
2911 case X86::BI__builtin_ia32_pternlogq512_mask:
2912 case X86::BI__builtin_ia32_pternlogq512_maskz:
2913 case X86::BI__builtin_ia32_pternlogd128_mask:
2914 case X86::BI__builtin_ia32_pternlogd128_maskz:
2915 case X86::BI__builtin_ia32_pternlogd256_mask:
2916 case X86::BI__builtin_ia32_pternlogd256_maskz:
2917 case X86::BI__builtin_ia32_pternlogq128_mask:
2918 case X86::BI__builtin_ia32_pternlogq128_maskz:
2919 case X86::BI__builtin_ia32_pternlogq256_mask:
2920 case X86::BI__builtin_ia32_pternlogq256_maskz:
2921 i = 3; l = 0; u = 255;
2922 break;
Craig Topper9625db02017-03-12 22:19:10 +00002923 case X86::BI__builtin_ia32_gatherpfdpd:
2924 case X86::BI__builtin_ia32_gatherpfdps:
2925 case X86::BI__builtin_ia32_gatherpfqpd:
2926 case X86::BI__builtin_ia32_gatherpfqps:
2927 case X86::BI__builtin_ia32_scatterpfdpd:
2928 case X86::BI__builtin_ia32_scatterpfdps:
2929 case X86::BI__builtin_ia32_scatterpfqpd:
2930 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002931 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002932 break;
Craig Topper39c87102016-05-18 03:18:12 +00002933 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2934 case X86::BI__builtin_ia32_rndscaless_round_mask:
2935 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002936 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002937 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002938 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002939}
2940
Richard Smith55ce3522012-06-25 20:30:08 +00002941/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2942/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2943/// Returns true when the format fits the function and the FormatStringInfo has
2944/// been populated.
2945bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2946 FormatStringInfo *FSI) {
2947 FSI->HasVAListArg = Format->getFirstArg() == 0;
2948 FSI->FormatIdx = Format->getFormatIdx() - 1;
2949 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002950
Richard Smith55ce3522012-06-25 20:30:08 +00002951 // The way the format attribute works in GCC, the implicit this argument
2952 // of member functions is counted. However, it doesn't appear in our own
2953 // lists, so decrement format_idx in that case.
2954 if (IsCXXMember) {
2955 if(FSI->FormatIdx == 0)
2956 return false;
2957 --FSI->FormatIdx;
2958 if (FSI->FirstDataArg != 0)
2959 --FSI->FirstDataArg;
2960 }
2961 return true;
2962}
Mike Stump11289f42009-09-09 15:08:12 +00002963
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002964/// Checks if a the given expression evaluates to null.
2965///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002966/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002967static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002968 // If the expression has non-null type, it doesn't evaluate to null.
2969 if (auto nullability
2970 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2971 if (*nullability == NullabilityKind::NonNull)
2972 return false;
2973 }
2974
Ted Kremeneka146db32014-01-17 06:24:47 +00002975 // As a special case, transparent unions initialized with zero are
2976 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002977 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002978 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2979 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002980 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002981 if (const InitListExpr *ILE =
2982 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002983 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002984 }
2985
2986 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002987 return (!Expr->isValueDependent() &&
2988 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2989 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002990}
2991
2992static void CheckNonNullArgument(Sema &S,
2993 const Expr *ArgExpr,
2994 SourceLocation CallSiteLoc) {
2995 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002996 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2997 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002998}
2999
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003000bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3001 FormatStringInfo FSI;
3002 if ((GetFormatStringType(Format) == FST_NSString) &&
3003 getFormatStringInfo(Format, false, &FSI)) {
3004 Idx = FSI.FormatIdx;
3005 return true;
3006 }
3007 return false;
3008}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003009
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003010/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003011/// as formatting string to formatting method.
3012static void
3013DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3014 const NamedDecl *FDecl,
3015 Expr **Args,
3016 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003017 unsigned Idx = 0;
3018 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003019 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3020 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003021 Idx = 2;
3022 Format = true;
3023 }
3024 else
3025 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3026 if (S.GetFormatNSStringIdx(I, Idx)) {
3027 Format = true;
3028 break;
3029 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003030 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003031 if (!Format || NumArgs <= Idx)
3032 return;
3033 const Expr *FormatExpr = Args[Idx];
3034 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3035 FormatExpr = CSCE->getSubExpr();
3036 const StringLiteral *FormatString;
3037 if (const ObjCStringLiteral *OSL =
3038 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3039 FormatString = OSL->getString();
3040 else
3041 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3042 if (!FormatString)
3043 return;
3044 if (S.FormatStringHasSArg(FormatString)) {
3045 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3046 << "%s" << 1 << 1;
3047 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3048 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003049 }
3050}
3051
Douglas Gregorb4866e82015-06-19 18:13:19 +00003052/// Determine whether the given type has a non-null nullability annotation.
3053static bool isNonNullType(ASTContext &ctx, QualType type) {
3054 if (auto nullability = type->getNullability(ctx))
3055 return *nullability == NullabilityKind::NonNull;
3056
3057 return false;
3058}
3059
Ted Kremenek2bc73332014-01-17 06:24:43 +00003060static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00003061 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003062 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00003063 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00003064 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003065 assert((FDecl || Proto) && "Need a function declaration or prototype");
3066
Ted Kremenek9aedc152014-01-17 06:24:56 +00003067 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00003068 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00003069 if (FDecl) {
3070 // Handle the nonnull attribute on the function/method declaration itself.
3071 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3072 if (!NonNull->args_size()) {
3073 // Easy case: all pointer arguments are nonnull.
3074 for (const auto *Arg : Args)
3075 if (S.isValidPointerAttrType(Arg->getType()))
3076 CheckNonNullArgument(S, Arg, CallSiteLoc);
3077 return;
3078 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003079
Joel E. Denny81508102018-03-13 14:51:22 +00003080 for (const ParamIdx &Idx : NonNull->args()) {
3081 unsigned IdxAST = Idx.getASTIndex();
3082 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00003083 continue;
3084 if (NonNullArgs.empty())
3085 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00003086 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003087 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003088 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003089 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003090
Douglas Gregorb4866e82015-06-19 18:13:19 +00003091 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3092 // Handle the nonnull attribute on the parameters of the
3093 // function/method.
3094 ArrayRef<ParmVarDecl*> parms;
3095 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3096 parms = FD->parameters();
3097 else
3098 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3099
3100 unsigned ParamIndex = 0;
3101 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3102 I != E; ++I, ++ParamIndex) {
3103 const ParmVarDecl *PVD = *I;
3104 if (PVD->hasAttr<NonNullAttr>() ||
3105 isNonNullType(S.Context, PVD->getType())) {
3106 if (NonNullArgs.empty())
3107 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00003108
Douglas Gregorb4866e82015-06-19 18:13:19 +00003109 NonNullArgs.set(ParamIndex);
3110 }
3111 }
3112 } else {
3113 // If we have a non-function, non-method declaration but no
3114 // function prototype, try to dig out the function prototype.
3115 if (!Proto) {
3116 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3117 QualType type = VD->getType().getNonReferenceType();
3118 if (auto pointerType = type->getAs<PointerType>())
3119 type = pointerType->getPointeeType();
3120 else if (auto blockType = type->getAs<BlockPointerType>())
3121 type = blockType->getPointeeType();
3122 // FIXME: data member pointers?
3123
3124 // Dig out the function prototype, if there is one.
3125 Proto = type->getAs<FunctionProtoType>();
3126 }
3127 }
3128
3129 // Fill in non-null argument information from the nullability
3130 // information on the parameter types (if we have them).
3131 if (Proto) {
3132 unsigned Index = 0;
3133 for (auto paramType : Proto->getParamTypes()) {
3134 if (isNonNullType(S.Context, paramType)) {
3135 if (NonNullArgs.empty())
3136 NonNullArgs.resize(Args.size());
3137
3138 NonNullArgs.set(Index);
3139 }
3140
3141 ++Index;
3142 }
3143 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003144 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003145
Douglas Gregorb4866e82015-06-19 18:13:19 +00003146 // Check for non-null arguments.
3147 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3148 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00003149 if (NonNullArgs[ArgIndex])
3150 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003151 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003152}
3153
Richard Smith55ce3522012-06-25 20:30:08 +00003154/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00003155/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3156/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003157void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00003158 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3159 bool IsMemberFunction, SourceLocation Loc,
3160 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00003161 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00003162 if (CurContext->isDependentContext())
3163 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00003164
Ted Kremenekb8176da2010-09-09 04:33:05 +00003165 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003166 llvm::SmallBitVector CheckedVarArgs;
3167 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003168 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003169 // Only create vector if there are format attributes.
3170 CheckedVarArgs.resize(Args.size());
3171
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003172 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003173 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003174 }
Richard Smithd7293d72013-08-05 18:49:43 +00003175 }
Richard Smith55ce3522012-06-25 20:30:08 +00003176
3177 // Refuse POD arguments that weren't caught by the format string
3178 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003179 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3180 if (CallType != VariadicDoesNotApply &&
3181 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003182 unsigned NumParams = Proto ? Proto->getNumParams()
3183 : FDecl && isa<FunctionDecl>(FDecl)
3184 ? cast<FunctionDecl>(FDecl)->getNumParams()
3185 : FDecl && isa<ObjCMethodDecl>(FDecl)
3186 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3187 : 0;
3188
Alp Toker9cacbab2014-01-20 20:26:09 +00003189 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003190 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003191 if (const Expr *Arg = Args[ArgIdx]) {
3192 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3193 checkVariadicArgument(Arg, CallType);
3194 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003195 }
Richard Smithd7293d72013-08-05 18:49:43 +00003196 }
Mike Stump11289f42009-09-09 15:08:12 +00003197
Douglas Gregorb4866e82015-06-19 18:13:19 +00003198 if (FDecl || Proto) {
3199 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003200
Richard Trieu41bc0992013-06-22 00:20:41 +00003201 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003202 if (FDecl) {
3203 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003204 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003205 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003206 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003207
3208 if (FD)
3209 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003210}
3211
3212/// CheckConstructorCall - Check a constructor call for correctness and safety
3213/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003214void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3215 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003216 const FunctionProtoType *Proto,
3217 SourceLocation Loc) {
3218 VariadicCallType CallType =
3219 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003220 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3221 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003222}
3223
3224/// CheckFunctionCall - Check a direct function call for various correctness
3225/// and safety properties not strictly enforced by the C type system.
3226bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3227 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003228 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3229 isa<CXXMethodDecl>(FDecl);
3230 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3231 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003232 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3233 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003234 Expr** Args = TheCall->getArgs();
3235 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003236
3237 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003238 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003239 // If this is a call to a member operator, hide the first argument
3240 // from checkCall.
3241 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003242 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003243 ++Args;
3244 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003245 } else if (IsMemberFunction)
3246 ImplicitThis =
3247 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3248
3249 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003250 IsMemberFunction, TheCall->getRParenLoc(),
3251 TheCall->getCallee()->getSourceRange(), CallType);
3252
3253 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3254 // None of the checks below are needed for functions that don't have
3255 // simple names (e.g., C++ conversion functions).
3256 if (!FnInfo)
3257 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003258
Richard Trieua7f30b12016-12-06 01:42:28 +00003259 CheckAbsoluteValueFunction(TheCall, FDecl);
3260 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003261
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003262 if (getLangOpts().ObjC1)
3263 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003264
Anna Zaks22122702012-01-17 00:37:07 +00003265 unsigned CMId = FDecl->getMemoryFunctionKind();
3266 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003267 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003268
Anna Zaks201d4892012-01-13 21:52:01 +00003269 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003270 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003271 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003272 else if (CMId == Builtin::BIstrncat)
3273 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003274 else
Anna Zaks22122702012-01-17 00:37:07 +00003275 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003276
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003277 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003278}
3279
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003280bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003281 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003282 VariadicCallType CallType =
3283 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003284
George Burgess IVce6284b2017-01-28 02:19:40 +00003285 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3286 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003287 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003288
3289 return false;
3290}
3291
Richard Trieu664c4c62013-06-20 21:03:13 +00003292bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3293 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003294 QualType Ty;
3295 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003296 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003297 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003298 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003299 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003300 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003301
Douglas Gregorb4866e82015-06-19 18:13:19 +00003302 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3303 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003304 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003305
Richard Trieu664c4c62013-06-20 21:03:13 +00003306 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003307 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003308 CallType = VariadicDoesNotApply;
3309 } else if (Ty->isBlockPointerType()) {
3310 CallType = VariadicBlock;
3311 } else { // Ty->isFunctionPointerType()
3312 CallType = VariadicFunction;
3313 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003314
George Burgess IVce6284b2017-01-28 02:19:40 +00003315 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003316 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3317 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003318 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003319
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003320 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003321}
3322
Richard Trieu41bc0992013-06-22 00:20:41 +00003323/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3324/// such as function pointers returned from functions.
3325bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003326 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003327 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003328 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003329 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003330 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003331 TheCall->getCallee()->getSourceRange(), CallType);
3332
3333 return false;
3334}
3335
Tim Northovere94a34c2014-03-11 10:49:14 +00003336static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003337 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003338 return false;
3339
JF Bastiendda2cb12016-04-18 18:01:49 +00003340 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003341 switch (Op) {
3342 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003343 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003344 llvm_unreachable("There is no ordering argument for an init");
3345
3346 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003347 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003348 case AtomicExpr::AO__atomic_load_n:
3349 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003350 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3351 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003352
3353 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003354 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003355 case AtomicExpr::AO__atomic_store:
3356 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003357 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3358 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3359 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003360
3361 default:
3362 return true;
3363 }
3364}
3365
Richard Smithfeea8832012-04-12 05:08:17 +00003366ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3367 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003368 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3369 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003370
Yaxun Liu39195062017-08-04 18:16:31 +00003371 // All the non-OpenCL operations take one of the following forms.
3372 // The OpenCL operations take the __c11 forms with one extra argument for
3373 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003374 enum {
3375 // C __c11_atomic_init(A *, C)
3376 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003377
Richard Smithfeea8832012-04-12 05:08:17 +00003378 // C __c11_atomic_load(A *, int)
3379 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003380
Richard Smithfeea8832012-04-12 05:08:17 +00003381 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003382 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003383
Eric Fiselier8d662442016-03-30 23:39:56 +00003384 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003385 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003386
Richard Smithfeea8832012-04-12 05:08:17 +00003387 // C __c11_atomic_add(A *, M, int)
3388 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003389
Richard Smithfeea8832012-04-12 05:08:17 +00003390 // C __atomic_exchange_n(A *, CP, int)
3391 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003392
Richard Smithfeea8832012-04-12 05:08:17 +00003393 // void __atomic_exchange(A *, C *, CP, int)
3394 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003395
Richard Smithfeea8832012-04-12 05:08:17 +00003396 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3397 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003398
Richard Smithfeea8832012-04-12 05:08:17 +00003399 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3400 GNUCmpXchg
3401 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003402
Yaxun Liu39195062017-08-04 18:16:31 +00003403 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003404 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3405 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003406 // where:
3407 // C is an appropriate type,
3408 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3409 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3410 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3411 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003412
Yaxun Liu39195062017-08-04 18:16:31 +00003413 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3414 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3415 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003416 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3417 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3418 AtomicExpr::AO__atomic_load,
3419 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003420 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3421 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3422 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3423 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3424 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003425 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3426 Op == AtomicExpr::AO__atomic_store_n ||
3427 Op == AtomicExpr::AO__atomic_exchange_n ||
3428 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3429 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003430 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003431
3432 switch (Op) {
3433 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003434 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003435 Form = Init;
3436 break;
3437
3438 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003439 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003440 case AtomicExpr::AO__atomic_load_n:
3441 Form = Load;
3442 break;
3443
Richard Smithfeea8832012-04-12 05:08:17 +00003444 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003445 Form = LoadCopy;
3446 break;
3447
3448 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003449 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003450 case AtomicExpr::AO__atomic_store:
3451 case AtomicExpr::AO__atomic_store_n:
3452 Form = Copy;
3453 break;
3454
3455 case AtomicExpr::AO__c11_atomic_fetch_add:
3456 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003457 case AtomicExpr::AO__opencl_atomic_fetch_add:
3458 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3459 case AtomicExpr::AO__opencl_atomic_fetch_min:
3460 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003461 case AtomicExpr::AO__atomic_fetch_add:
3462 case AtomicExpr::AO__atomic_fetch_sub:
3463 case AtomicExpr::AO__atomic_add_fetch:
3464 case AtomicExpr::AO__atomic_sub_fetch:
3465 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003466 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003467 case AtomicExpr::AO__c11_atomic_fetch_and:
3468 case AtomicExpr::AO__c11_atomic_fetch_or:
3469 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003470 case AtomicExpr::AO__opencl_atomic_fetch_and:
3471 case AtomicExpr::AO__opencl_atomic_fetch_or:
3472 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003473 case AtomicExpr::AO__atomic_fetch_and:
3474 case AtomicExpr::AO__atomic_fetch_or:
3475 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003476 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003477 case AtomicExpr::AO__atomic_and_fetch:
3478 case AtomicExpr::AO__atomic_or_fetch:
3479 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003480 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003481 Form = Arithmetic;
3482 break;
3483
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003484 case AtomicExpr::AO__atomic_fetch_min:
3485 case AtomicExpr::AO__atomic_fetch_max:
3486 IsMinMax = true;
3487 Form = Arithmetic;
3488 break;
3489
Richard Smithfeea8832012-04-12 05:08:17 +00003490 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003491 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003492 case AtomicExpr::AO__atomic_exchange_n:
3493 Form = Xchg;
3494 break;
3495
3496 case AtomicExpr::AO__atomic_exchange:
3497 Form = GNUXchg;
3498 break;
3499
3500 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3501 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003502 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3503 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003504 Form = C11CmpXchg;
3505 break;
3506
3507 case AtomicExpr::AO__atomic_compare_exchange:
3508 case AtomicExpr::AO__atomic_compare_exchange_n:
3509 Form = GNUCmpXchg;
3510 break;
3511 }
3512
Yaxun Liu39195062017-08-04 18:16:31 +00003513 unsigned AdjustedNumArgs = NumArgs[Form];
3514 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3515 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003516 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003517 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003518 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003519 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003520 << TheCall->getCallee()->getSourceRange();
3521 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003522 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3523 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003524 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003525 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003526 << TheCall->getCallee()->getSourceRange();
3527 return ExprError();
3528 }
3529
Richard Smithfeea8832012-04-12 05:08:17 +00003530 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003531 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003532 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3533 if (ConvertedPtr.isInvalid())
3534 return ExprError();
3535
3536 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003537 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3538 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003539 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003540 << Ptr->getType() << Ptr->getSourceRange();
3541 return ExprError();
3542 }
3543
Richard Smithfeea8832012-04-12 05:08:17 +00003544 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3545 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3546 QualType ValType = AtomTy; // 'C'
3547 if (IsC11) {
3548 if (!AtomTy->isAtomicType()) {
3549 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3550 << Ptr->getType() << Ptr->getSourceRange();
3551 return ExprError();
3552 }
Yaxun Liu39195062017-08-04 18:16:31 +00003553 if (AtomTy.isConstQualified() ||
3554 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003555 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003556 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3557 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003558 return ExprError();
3559 }
Richard Smithfeea8832012-04-12 05:08:17 +00003560 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003561 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003562 if (ValType.isConstQualified()) {
3563 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3564 << Ptr->getType() << Ptr->getSourceRange();
3565 return ExprError();
3566 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003567 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003568
Richard Smithfeea8832012-04-12 05:08:17 +00003569 // For an arithmetic operation, the implied arithmetic must be well-formed.
3570 if (Form == Arithmetic) {
3571 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003572 if (IsAddSub && !ValType->isIntegerType()
3573 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003574 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3575 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3576 return ExprError();
3577 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003578 if (IsMinMax) {
3579 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3580 if (!BT || (BT->getKind() != BuiltinType::Int &&
3581 BT->getKind() != BuiltinType::UInt)) {
3582 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3583 return ExprError();
3584 }
3585 }
3586 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003587 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3588 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3589 return ExprError();
3590 }
David Majnemere85cff82015-01-28 05:48:06 +00003591 if (IsC11 && ValType->isPointerType() &&
3592 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3593 diag::err_incomplete_type)) {
3594 return ExprError();
3595 }
Richard Smithfeea8832012-04-12 05:08:17 +00003596 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3597 // For __atomic_*_n operations, the value type must be a scalar integral or
3598 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003599 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003600 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3601 return ExprError();
3602 }
3603
Eli Friedmanaa769812013-09-11 03:49:34 +00003604 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3605 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003606 // For GNU atomics, require a trivially-copyable type. This is not part of
3607 // the GNU atomics specification, but we enforce it for sanity.
3608 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003609 << Ptr->getType() << Ptr->getSourceRange();
3610 return ExprError();
3611 }
3612
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003613 switch (ValType.getObjCLifetime()) {
3614 case Qualifiers::OCL_None:
3615 case Qualifiers::OCL_ExplicitNone:
3616 // okay
3617 break;
3618
3619 case Qualifiers::OCL_Weak:
3620 case Qualifiers::OCL_Strong:
3621 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003622 // FIXME: Can this happen? By this point, ValType should be known
3623 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003624 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3625 << ValType << Ptr->getSourceRange();
3626 return ExprError();
3627 }
3628
JF Bastien7f0a05a2018-05-25 00:07:09 +00003629 // All atomic operations have an overload which takes a pointer to a volatile
3630 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3631 // into the result or the other operands. Similarly atomic_load takes a
3632 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003633 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003634 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003635 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003636 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3637 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003638 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003639 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003640 ResultType = Context.BoolTy;
3641
Richard Smithfeea8832012-04-12 05:08:17 +00003642 // The type of a parameter passed 'by value'. In the GNU atomics, such
3643 // arguments are actually passed as pointers.
3644 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003645 bool IsPassedByAddress = false;
3646 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003647 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003648 IsPassedByAddress = true;
3649 }
Richard Smithfeea8832012-04-12 05:08:17 +00003650
JF Bastien7f0a05a2018-05-25 00:07:09 +00003651 // The first argument's non-CV pointer type is used to deduce the type of
3652 // subsequent arguments, except for:
3653 // - weak flag (always converted to bool)
3654 // - memory order (always converted to int)
3655 // - scope (always converted to int)
3656 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003657 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003658 if (i < NumVals[Form] + 1) {
3659 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003660 case 0:
3661 // The first argument is always a pointer. It has a fixed type.
3662 // It is always dereferenced, a nullptr is undefined.
3663 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3664 // Nothing else to do: we already know all we want about this pointer.
3665 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003666 case 1:
3667 // The second argument is the non-atomic operand. For arithmetic, this
3668 // is always passed by value, and for a compare_exchange it is always
3669 // passed by address. For the rest, GNU uses by-address and C11 uses
3670 // by-value.
3671 assert(Form != Load);
3672 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3673 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003674 else if (Form == Copy || Form == Xchg) {
3675 if (IsPassedByAddress)
3676 // The value pointer is always dereferenced, a nullptr is undefined.
3677 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003678 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003679 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003680 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003681 else {
3682 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003683 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003684 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003685 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003686 // Keep address space of non-atomic pointer type.
3687 if (const PointerType *PtrTy =
3688 ValArg->getType()->getAs<PointerType>()) {
3689 AS = PtrTy->getPointeeType().getAddressSpace();
3690 }
3691 Ty = Context.getPointerType(
3692 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3693 }
Richard Smithfeea8832012-04-12 05:08:17 +00003694 break;
3695 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003696 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003697 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3698 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003699 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003700 Ty = ByValType;
3701 break;
3702 case 3:
3703 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3704 Ty = Context.BoolTy;
3705 break;
3706 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003707 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003708 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003709 Ty = Context.IntTy;
3710 }
Richard Smithfeea8832012-04-12 05:08:17 +00003711
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003712 InitializedEntity Entity =
3713 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003714 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003715 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3716 if (Arg.isInvalid())
3717 return true;
3718 TheCall->setArg(i, Arg.get());
3719 }
3720
Richard Smithfeea8832012-04-12 05:08:17 +00003721 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003722 SmallVector<Expr*, 5> SubExprs;
3723 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003724 switch (Form) {
3725 case Init:
3726 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003727 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003728 break;
3729 case Load:
3730 SubExprs.push_back(TheCall->getArg(1)); // Order
3731 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003732 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003733 case Copy:
3734 case Arithmetic:
3735 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003736 SubExprs.push_back(TheCall->getArg(2)); // Order
3737 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003738 break;
3739 case GNUXchg:
3740 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3741 SubExprs.push_back(TheCall->getArg(3)); // Order
3742 SubExprs.push_back(TheCall->getArg(1)); // Val1
3743 SubExprs.push_back(TheCall->getArg(2)); // Val2
3744 break;
3745 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003746 SubExprs.push_back(TheCall->getArg(3)); // Order
3747 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003748 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003749 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003750 break;
3751 case GNUCmpXchg:
3752 SubExprs.push_back(TheCall->getArg(4)); // Order
3753 SubExprs.push_back(TheCall->getArg(1)); // Val1
3754 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3755 SubExprs.push_back(TheCall->getArg(2)); // Val2
3756 SubExprs.push_back(TheCall->getArg(3)); // Weak
3757 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003758 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003759
3760 if (SubExprs.size() >= 2 && Form != Init) {
3761 llvm::APSInt Result(32);
3762 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3763 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003764 Diag(SubExprs[1]->getLocStart(),
3765 diag::warn_atomic_op_has_invalid_memory_order)
3766 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003767 }
3768
Yaxun Liu30d652a2017-08-15 16:02:49 +00003769 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3770 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3771 llvm::APSInt Result(32);
3772 if (Scope->isIntegerConstantExpr(Result, Context) &&
3773 !ScopeModel->isValid(Result.getZExtValue())) {
3774 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3775 << Scope->getSourceRange();
3776 }
3777 SubExprs.push_back(Scope);
3778 }
3779
Fariborz Jahanian615de762013-05-28 17:37:39 +00003780 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3781 SubExprs, ResultType, Op,
3782 TheCall->getRParenLoc());
3783
3784 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003785 Op == AtomicExpr::AO__c11_atomic_store ||
3786 Op == AtomicExpr::AO__opencl_atomic_load ||
3787 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003788 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003789 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3790 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3791 Op == AtomicExpr::AO__opencl_atomic_load)
3792 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003793
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003794 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003795}
3796
John McCall29ad95b2011-08-27 01:09:30 +00003797/// checkBuiltinArgument - Given a call to a builtin function, perform
3798/// normal type-checking on the given argument, updating the call in
3799/// place. This is useful when a builtin function requires custom
3800/// type-checking for some of its arguments but not necessarily all of
3801/// them.
3802///
3803/// Returns true on error.
3804static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3805 FunctionDecl *Fn = E->getDirectCallee();
3806 assert(Fn && "builtin call without direct callee!");
3807
3808 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3809 InitializedEntity Entity =
3810 InitializedEntity::InitializeParameter(S.Context, Param);
3811
3812 ExprResult Arg = E->getArg(0);
3813 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3814 if (Arg.isInvalid())
3815 return true;
3816
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003817 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003818 return false;
3819}
3820
Chris Lattnerdc046542009-05-08 06:58:22 +00003821/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3822/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3823/// type of its first argument. The main ActOnCallExpr routines have already
3824/// promoted the types of arguments because all of these calls are prototyped as
3825/// void(...).
3826///
3827/// This function goes through and does final semantic checking for these
3828/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003829ExprResult
3830Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003831 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003832 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3833 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3834
3835 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003836 if (TheCall->getNumArgs() < 1) {
3837 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3838 << 0 << 1 << TheCall->getNumArgs()
3839 << TheCall->getCallee()->getSourceRange();
3840 return ExprError();
3841 }
Mike Stump11289f42009-09-09 15:08:12 +00003842
Chris Lattnerdc046542009-05-08 06:58:22 +00003843 // Inspect the first argument of the atomic builtin. This should always be
3844 // a pointer type, whose element is an integral scalar or pointer type.
3845 // Because it is a pointer type, we don't have to worry about any implicit
3846 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003847 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003848 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003849 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3850 if (FirstArgResult.isInvalid())
3851 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003852 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003853 TheCall->setArg(0, FirstArg);
3854
John McCall31168b02011-06-15 23:02:42 +00003855 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3856 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003857 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3858 << FirstArg->getType() << FirstArg->getSourceRange();
3859 return ExprError();
3860 }
Mike Stump11289f42009-09-09 15:08:12 +00003861
John McCall31168b02011-06-15 23:02:42 +00003862 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003863 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003864 !ValType->isBlockPointerType()) {
3865 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3866 << FirstArg->getType() << FirstArg->getSourceRange();
3867 return ExprError();
3868 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003869
Aaron Ballmana383c942018-05-05 17:38:42 +00003870 if (ValType.isConstQualified()) {
3871 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3872 << FirstArg->getType() << FirstArg->getSourceRange();
3873 return ExprError();
3874 }
3875
John McCall31168b02011-06-15 23:02:42 +00003876 switch (ValType.getObjCLifetime()) {
3877 case Qualifiers::OCL_None:
3878 case Qualifiers::OCL_ExplicitNone:
3879 // okay
3880 break;
3881
3882 case Qualifiers::OCL_Weak:
3883 case Qualifiers::OCL_Strong:
3884 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003885 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003886 << ValType << FirstArg->getSourceRange();
3887 return ExprError();
3888 }
3889
John McCallb50451a2011-10-05 07:41:44 +00003890 // Strip any qualifiers off ValType.
3891 ValType = ValType.getUnqualifiedType();
3892
Chandler Carruth3973af72010-07-18 20:54:12 +00003893 // The majority of builtins return a value, but a few have special return
3894 // types, so allow them to override appropriately below.
3895 QualType ResultType = ValType;
3896
Chris Lattnerdc046542009-05-08 06:58:22 +00003897 // We need to figure out which concrete builtin this maps onto. For example,
3898 // __sync_fetch_and_add with a 2 byte object turns into
3899 // __sync_fetch_and_add_2.
3900#define BUILTIN_ROW(x) \
3901 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3902 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003903
Chris Lattnerdc046542009-05-08 06:58:22 +00003904 static const unsigned BuiltinIndices[][5] = {
3905 BUILTIN_ROW(__sync_fetch_and_add),
3906 BUILTIN_ROW(__sync_fetch_and_sub),
3907 BUILTIN_ROW(__sync_fetch_and_or),
3908 BUILTIN_ROW(__sync_fetch_and_and),
3909 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003910 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003911
Chris Lattnerdc046542009-05-08 06:58:22 +00003912 BUILTIN_ROW(__sync_add_and_fetch),
3913 BUILTIN_ROW(__sync_sub_and_fetch),
3914 BUILTIN_ROW(__sync_and_and_fetch),
3915 BUILTIN_ROW(__sync_or_and_fetch),
3916 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003917 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003918
Chris Lattnerdc046542009-05-08 06:58:22 +00003919 BUILTIN_ROW(__sync_val_compare_and_swap),
3920 BUILTIN_ROW(__sync_bool_compare_and_swap),
3921 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003922 BUILTIN_ROW(__sync_lock_release),
3923 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003924 };
Mike Stump11289f42009-09-09 15:08:12 +00003925#undef BUILTIN_ROW
3926
Chris Lattnerdc046542009-05-08 06:58:22 +00003927 // Determine the index of the size.
3928 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003929 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003930 case 1: SizeIndex = 0; break;
3931 case 2: SizeIndex = 1; break;
3932 case 4: SizeIndex = 2; break;
3933 case 8: SizeIndex = 3; break;
3934 case 16: SizeIndex = 4; break;
3935 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003936 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3937 << FirstArg->getType() << FirstArg->getSourceRange();
3938 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003939 }
Mike Stump11289f42009-09-09 15:08:12 +00003940
Chris Lattnerdc046542009-05-08 06:58:22 +00003941 // Each of these builtins has one pointer argument, followed by some number of
3942 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3943 // that we ignore. Find out which row of BuiltinIndices to read from as well
3944 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003945 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003946 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003947 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003948 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003949 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003950 case Builtin::BI__sync_fetch_and_add:
3951 case Builtin::BI__sync_fetch_and_add_1:
3952 case Builtin::BI__sync_fetch_and_add_2:
3953 case Builtin::BI__sync_fetch_and_add_4:
3954 case Builtin::BI__sync_fetch_and_add_8:
3955 case Builtin::BI__sync_fetch_and_add_16:
3956 BuiltinIndex = 0;
3957 break;
3958
3959 case Builtin::BI__sync_fetch_and_sub:
3960 case Builtin::BI__sync_fetch_and_sub_1:
3961 case Builtin::BI__sync_fetch_and_sub_2:
3962 case Builtin::BI__sync_fetch_and_sub_4:
3963 case Builtin::BI__sync_fetch_and_sub_8:
3964 case Builtin::BI__sync_fetch_and_sub_16:
3965 BuiltinIndex = 1;
3966 break;
3967
3968 case Builtin::BI__sync_fetch_and_or:
3969 case Builtin::BI__sync_fetch_and_or_1:
3970 case Builtin::BI__sync_fetch_and_or_2:
3971 case Builtin::BI__sync_fetch_and_or_4:
3972 case Builtin::BI__sync_fetch_and_or_8:
3973 case Builtin::BI__sync_fetch_and_or_16:
3974 BuiltinIndex = 2;
3975 break;
3976
3977 case Builtin::BI__sync_fetch_and_and:
3978 case Builtin::BI__sync_fetch_and_and_1:
3979 case Builtin::BI__sync_fetch_and_and_2:
3980 case Builtin::BI__sync_fetch_and_and_4:
3981 case Builtin::BI__sync_fetch_and_and_8:
3982 case Builtin::BI__sync_fetch_and_and_16:
3983 BuiltinIndex = 3;
3984 break;
Mike Stump11289f42009-09-09 15:08:12 +00003985
Douglas Gregor73722482011-11-28 16:30:08 +00003986 case Builtin::BI__sync_fetch_and_xor:
3987 case Builtin::BI__sync_fetch_and_xor_1:
3988 case Builtin::BI__sync_fetch_and_xor_2:
3989 case Builtin::BI__sync_fetch_and_xor_4:
3990 case Builtin::BI__sync_fetch_and_xor_8:
3991 case Builtin::BI__sync_fetch_and_xor_16:
3992 BuiltinIndex = 4;
3993 break;
3994
Hal Finkeld2208b52014-10-02 20:53:50 +00003995 case Builtin::BI__sync_fetch_and_nand:
3996 case Builtin::BI__sync_fetch_and_nand_1:
3997 case Builtin::BI__sync_fetch_and_nand_2:
3998 case Builtin::BI__sync_fetch_and_nand_4:
3999 case Builtin::BI__sync_fetch_and_nand_8:
4000 case Builtin::BI__sync_fetch_and_nand_16:
4001 BuiltinIndex = 5;
4002 WarnAboutSemanticsChange = true;
4003 break;
4004
Douglas Gregor73722482011-11-28 16:30:08 +00004005 case Builtin::BI__sync_add_and_fetch:
4006 case Builtin::BI__sync_add_and_fetch_1:
4007 case Builtin::BI__sync_add_and_fetch_2:
4008 case Builtin::BI__sync_add_and_fetch_4:
4009 case Builtin::BI__sync_add_and_fetch_8:
4010 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004011 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00004012 break;
4013
4014 case Builtin::BI__sync_sub_and_fetch:
4015 case Builtin::BI__sync_sub_and_fetch_1:
4016 case Builtin::BI__sync_sub_and_fetch_2:
4017 case Builtin::BI__sync_sub_and_fetch_4:
4018 case Builtin::BI__sync_sub_and_fetch_8:
4019 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004020 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00004021 break;
4022
4023 case Builtin::BI__sync_and_and_fetch:
4024 case Builtin::BI__sync_and_and_fetch_1:
4025 case Builtin::BI__sync_and_and_fetch_2:
4026 case Builtin::BI__sync_and_and_fetch_4:
4027 case Builtin::BI__sync_and_and_fetch_8:
4028 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004029 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00004030 break;
4031
4032 case Builtin::BI__sync_or_and_fetch:
4033 case Builtin::BI__sync_or_and_fetch_1:
4034 case Builtin::BI__sync_or_and_fetch_2:
4035 case Builtin::BI__sync_or_and_fetch_4:
4036 case Builtin::BI__sync_or_and_fetch_8:
4037 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004038 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00004039 break;
4040
4041 case Builtin::BI__sync_xor_and_fetch:
4042 case Builtin::BI__sync_xor_and_fetch_1:
4043 case Builtin::BI__sync_xor_and_fetch_2:
4044 case Builtin::BI__sync_xor_and_fetch_4:
4045 case Builtin::BI__sync_xor_and_fetch_8:
4046 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004047 BuiltinIndex = 10;
4048 break;
4049
4050 case Builtin::BI__sync_nand_and_fetch:
4051 case Builtin::BI__sync_nand_and_fetch_1:
4052 case Builtin::BI__sync_nand_and_fetch_2:
4053 case Builtin::BI__sync_nand_and_fetch_4:
4054 case Builtin::BI__sync_nand_and_fetch_8:
4055 case Builtin::BI__sync_nand_and_fetch_16:
4056 BuiltinIndex = 11;
4057 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00004058 break;
Mike Stump11289f42009-09-09 15:08:12 +00004059
Chris Lattnerdc046542009-05-08 06:58:22 +00004060 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004061 case Builtin::BI__sync_val_compare_and_swap_1:
4062 case Builtin::BI__sync_val_compare_and_swap_2:
4063 case Builtin::BI__sync_val_compare_and_swap_4:
4064 case Builtin::BI__sync_val_compare_and_swap_8:
4065 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004066 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00004067 NumFixed = 2;
4068 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004069
Chris Lattnerdc046542009-05-08 06:58:22 +00004070 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004071 case Builtin::BI__sync_bool_compare_and_swap_1:
4072 case Builtin::BI__sync_bool_compare_and_swap_2:
4073 case Builtin::BI__sync_bool_compare_and_swap_4:
4074 case Builtin::BI__sync_bool_compare_and_swap_8:
4075 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004076 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00004077 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00004078 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004079 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004080
JF Bastien7f0a05a2018-05-25 00:07:09 +00004081 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00004082 case Builtin::BI__sync_lock_test_and_set_1:
4083 case Builtin::BI__sync_lock_test_and_set_2:
4084 case Builtin::BI__sync_lock_test_and_set_4:
4085 case Builtin::BI__sync_lock_test_and_set_8:
4086 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004087 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00004088 break;
4089
Chris Lattnerdc046542009-05-08 06:58:22 +00004090 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00004091 case Builtin::BI__sync_lock_release_1:
4092 case Builtin::BI__sync_lock_release_2:
4093 case Builtin::BI__sync_lock_release_4:
4094 case Builtin::BI__sync_lock_release_8:
4095 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004096 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00004097 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00004098 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004099 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004100
4101 case Builtin::BI__sync_swap:
4102 case Builtin::BI__sync_swap_1:
4103 case Builtin::BI__sync_swap_2:
4104 case Builtin::BI__sync_swap_4:
4105 case Builtin::BI__sync_swap_8:
4106 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004107 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00004108 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00004109 }
Mike Stump11289f42009-09-09 15:08:12 +00004110
Chris Lattnerdc046542009-05-08 06:58:22 +00004111 // Now that we know how many fixed arguments we expect, first check that we
4112 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004113 if (TheCall->getNumArgs() < 1+NumFixed) {
4114 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4115 << 0 << 1+NumFixed << TheCall->getNumArgs()
4116 << TheCall->getCallee()->getSourceRange();
4117 return ExprError();
4118 }
Mike Stump11289f42009-09-09 15:08:12 +00004119
Hal Finkeld2208b52014-10-02 20:53:50 +00004120 if (WarnAboutSemanticsChange) {
4121 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4122 << TheCall->getCallee()->getSourceRange();
4123 }
4124
Chris Lattner5b9241b2009-05-08 15:36:58 +00004125 // Get the decl for the concrete builtin from this, we can tell what the
4126 // concrete integer type we should convert to is.
4127 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00004128 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004129 FunctionDecl *NewBuiltinDecl;
4130 if (NewBuiltinID == BuiltinID)
4131 NewBuiltinDecl = FDecl;
4132 else {
4133 // Perform builtin lookup to avoid redeclaring it.
4134 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4135 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4136 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4137 assert(Res.getFoundDecl());
4138 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004139 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004140 return ExprError();
4141 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004142
John McCallcf142162010-08-07 06:22:56 +00004143 // The first argument --- the pointer --- has a fixed type; we
4144 // deduce the types of the rest of the arguments accordingly. Walk
4145 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00004146 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004147 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00004148
Chris Lattnerdc046542009-05-08 06:58:22 +00004149 // GCC does an implicit conversion to the pointer or integer ValType. This
4150 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00004151 // Initialize the argument.
4152 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4153 ValType, /*consume*/ false);
4154 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00004155 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004156 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004157
Chris Lattnerdc046542009-05-08 06:58:22 +00004158 // Okay, we have something that *can* be converted to the right type. Check
4159 // to see if there is a potentially weird extension going on here. This can
4160 // happen when you do an atomic operation on something like an char* and
4161 // pass in 42. The 42 gets converted to char. This is even more strange
4162 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00004163 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004164 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004165 }
Mike Stump11289f42009-09-09 15:08:12 +00004166
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004167 ASTContext& Context = this->getASTContext();
4168
4169 // Create a new DeclRefExpr to refer to the new decl.
4170 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4171 Context,
4172 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004173 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004174 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004175 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004176 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004177 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004178 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004179
Chris Lattnerdc046542009-05-08 06:58:22 +00004180 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004181 // FIXME: This loses syntactic information.
4182 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4183 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4184 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004185 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004186
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004187 // Change the result type of the call to match the original value type. This
4188 // is arbitrary, but the codegen for these builtins ins design to handle it
4189 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004190 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004191
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004192 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004193}
4194
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004195/// SemaBuiltinNontemporalOverloaded - We have a call to
4196/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4197/// overloaded function based on the pointer type of its last argument.
4198///
4199/// This function goes through and does final semantic checking for these
4200/// builtins.
4201ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4202 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4203 DeclRefExpr *DRE =
4204 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4205 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4206 unsigned BuiltinID = FDecl->getBuiltinID();
4207 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4208 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4209 "Unexpected nontemporal load/store builtin!");
4210 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4211 unsigned numArgs = isStore ? 2 : 1;
4212
4213 // Ensure that we have the proper number of arguments.
4214 if (checkArgCount(*this, TheCall, numArgs))
4215 return ExprError();
4216
4217 // Inspect the last argument of the nontemporal builtin. This should always
4218 // be a pointer type, from which we imply the type of the memory access.
4219 // Because it is a pointer type, we don't have to worry about any implicit
4220 // casts here.
4221 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4222 ExprResult PointerArgResult =
4223 DefaultFunctionArrayLvalueConversion(PointerArg);
4224
4225 if (PointerArgResult.isInvalid())
4226 return ExprError();
4227 PointerArg = PointerArgResult.get();
4228 TheCall->setArg(numArgs - 1, PointerArg);
4229
4230 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4231 if (!pointerType) {
4232 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4233 << PointerArg->getType() << PointerArg->getSourceRange();
4234 return ExprError();
4235 }
4236
4237 QualType ValType = pointerType->getPointeeType();
4238
4239 // Strip any qualifiers off ValType.
4240 ValType = ValType.getUnqualifiedType();
4241 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4242 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4243 !ValType->isVectorType()) {
4244 Diag(DRE->getLocStart(),
4245 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4246 << PointerArg->getType() << PointerArg->getSourceRange();
4247 return ExprError();
4248 }
4249
4250 if (!isStore) {
4251 TheCall->setType(ValType);
4252 return TheCallResult;
4253 }
4254
4255 ExprResult ValArg = TheCall->getArg(0);
4256 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4257 Context, ValType, /*consume*/ false);
4258 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4259 if (ValArg.isInvalid())
4260 return ExprError();
4261
4262 TheCall->setArg(0, ValArg.get());
4263 TheCall->setType(Context.VoidTy);
4264 return TheCallResult;
4265}
4266
Chris Lattner6436fb62009-02-18 06:01:06 +00004267/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004268/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004269/// Note: It might also make sense to do the UTF-16 conversion here (would
4270/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004271bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004272 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004273 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4274
Douglas Gregorfb65e592011-07-27 05:40:30 +00004275 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004276 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4277 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004278 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004279 }
Mike Stump11289f42009-09-09 15:08:12 +00004280
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004281 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004282 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004283 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004284 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4285 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4286 llvm::UTF16 *ToPtr = &ToBuf[0];
4287
4288 llvm::ConversionResult Result =
4289 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4290 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004291 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004292 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004293 Diag(Arg->getLocStart(),
4294 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4295 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004296 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004297}
4298
Mehdi Amini06d367c2016-10-24 20:39:34 +00004299/// CheckObjCString - Checks that the format string argument to the os_log()
4300/// and os_trace() functions is correct, and converts it to const char *.
4301ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4302 Arg = Arg->IgnoreParenCasts();
4303 auto *Literal = dyn_cast<StringLiteral>(Arg);
4304 if (!Literal) {
4305 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4306 Literal = ObjcLiteral->getString();
4307 }
4308 }
4309
4310 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4311 return ExprError(
4312 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4313 << Arg->getSourceRange());
4314 }
4315
4316 ExprResult Result(Literal);
4317 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4318 InitializedEntity Entity =
4319 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4320 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4321 return Result;
4322}
4323
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004324/// Check that the user is calling the appropriate va_start builtin for the
4325/// target and calling convention.
4326static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4327 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4328 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004329 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004330 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004331 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4332 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004333 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004334 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4335 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4336 if (IsMSVAStart) {
4337 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004338 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004339 return S.Diag(Fn->getLocStart(),
4340 diag::err_ms_va_start_used_in_sysv_function);
4341 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004342 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004343 // On x64 Windows, don't allow this in System V ABI functions.
4344 // (Yes, that means there's no corresponding way to support variadic
4345 // System V ABI functions on Windows.)
4346 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004347 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004348 return S.Diag(Fn->getLocStart(),
4349 diag::err_va_start_used_in_wrong_abi_function)
4350 << !IsWindows;
4351 }
4352 return false;
4353 }
4354
4355 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004356 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004357 return false;
4358}
4359
4360static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4361 ParmVarDecl **LastParam = nullptr) {
4362 // Determine whether the current function, block, or obj-c method is variadic
4363 // and get its parameter list.
4364 bool IsVariadic = false;
4365 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004366 DeclContext *Caller = S.CurContext;
4367 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4368 IsVariadic = Block->isVariadic();
4369 Params = Block->parameters();
4370 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004371 IsVariadic = FD->isVariadic();
4372 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004373 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004374 IsVariadic = MD->isVariadic();
4375 // FIXME: This isn't correct for methods (results in bogus warning).
4376 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004377 } else if (isa<CapturedDecl>(Caller)) {
4378 // We don't support va_start in a CapturedDecl.
4379 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4380 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004381 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004382 // This must be some other declcontext that parses exprs.
4383 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4384 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004385 }
4386
4387 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004388 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004389 return true;
4390 }
4391
4392 if (LastParam)
4393 *LastParam = Params.empty() ? nullptr : Params.back();
4394
4395 return false;
4396}
4397
Aaron Ballman9360cb02018-06-19 14:36:04 +00004398/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4399/// for validity. Emit an error and return true on failure; return false
4400/// on success.
4401bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
4402 Expr *Fn = TheCall->getCallee();
4403
4404 if (checkVAStartABI(*this, BuiltinID, Fn))
4405 return true;
4406
4407 if (TheCall->getNumArgs() > 2) {
4408 Diag(TheCall->getArg(2)->getLocStart(),
4409 diag::err_typecheck_call_too_many_args)
4410 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4411 << Fn->getSourceRange()
4412 << SourceRange(TheCall->getArg(2)->getLocStart(),
4413 (*(TheCall->arg_end()-1))->getLocEnd());
4414 return true;
4415 }
4416
4417 if (TheCall->getNumArgs() < 2) {
4418 return Diag(TheCall->getLocEnd(),
4419 diag::err_typecheck_call_too_few_args_at_least)
4420 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
4421 }
4422
4423 // Type-check the first argument normally.
4424 if (checkBuiltinArgument(*this, TheCall, 0))
4425 return true;
4426
4427 // Check that the current function is variadic, and get its last parameter.
4428 ParmVarDecl *LastParam;
4429 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
4430 return true;
4431
4432 // Verify that the second argument to the builtin is the last argument of the
4433 // current function or method.
4434 bool SecondArgIsLastNamedArgument = false;
4435 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4436
4437 // These are valid if SecondArgIsLastNamedArgument is false after the next
4438 // block.
4439 QualType Type;
4440 SourceLocation ParamLoc;
4441 bool IsCRegister = false;
4442
4443 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4444 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4445 SecondArgIsLastNamedArgument = PV == LastParam;
4446
4447 Type = PV->getType();
4448 ParamLoc = PV->getLocation();
4449 IsCRegister =
4450 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4451 }
4452 }
4453
4454 if (!SecondArgIsLastNamedArgument)
4455 Diag(TheCall->getArg(1)->getLocStart(),
4456 diag::warn_second_arg_of_va_start_not_last_named_param);
4457 else if (IsCRegister || Type->isReferenceType() ||
4458 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4459 // Promotable integers are UB, but enumerations need a bit of
4460 // extra checking to see what their promotable type actually is.
4461 if (!Type->isPromotableIntegerType())
4462 return false;
4463 if (!Type->isEnumeralType())
4464 return true;
4465 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4466 return !(ED &&
4467 Context.typesAreCompatible(ED->getPromotionType(), Type));
4468 }()) {
4469 unsigned Reason = 0;
4470 if (Type->isReferenceType()) Reason = 1;
4471 else if (IsCRegister) Reason = 2;
4472 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
4473 Diag(ParamLoc, diag::note_parameter_type) << Type;
4474 }
4475
4476 TheCall->setType(Context.VoidTy);
4477 return false;
4478}
4479
4480bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4481 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4482 // const char *named_addr);
4483
4484 Expr *Func = Call->getCallee();
4485
4486 if (Call->getNumArgs() < 3)
4487 return Diag(Call->getLocEnd(),
4488 diag::err_typecheck_call_too_few_args_at_least)
4489 << 0 /*function call*/ << 3 << Call->getNumArgs();
4490
4491 // Type-check the first argument normally.
4492 if (checkBuiltinArgument(*this, Call, 0))
4493 return true;
4494
4495 // Check that the current function is variadic.
4496 if (checkVAStartIsInVariadicFunction(*this, Func))
4497 return true;
4498
4499 // __va_start on Windows does not validate the parameter qualifiers
4500
4501 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4502 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4503
4504 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4505 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4506
4507 const QualType &ConstCharPtrTy =
4508 Context.getPointerType(Context.CharTy.withConst());
4509 if (!Arg1Ty->isPointerType() ||
4510 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4511 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4512 << Arg1->getType() << ConstCharPtrTy
4513 << 1 /* different class */
4514 << 0 /* qualifier difference */
4515 << 3 /* parameter mismatch */
4516 << 2 << Arg1->getType() << ConstCharPtrTy;
4517
4518 const QualType SizeTy = Context.getSizeType();
4519 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4520 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4521 << Arg2->getType() << SizeTy
4522 << 1 /* different class */
4523 << 0 /* qualifier difference */
4524 << 3 /* parameter mismatch */
4525 << 3 << Arg2->getType() << SizeTy;
4526
4527 return false;
4528}
4529
4530/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4531/// friends. This is declared to take (...), so we have to check everything.
4532bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4533 if (TheCall->getNumArgs() < 2)
4534 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4535 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4536 if (TheCall->getNumArgs() > 2)
4537 return Diag(TheCall->getArg(2)->getLocStart(),
4538 diag::err_typecheck_call_too_many_args)
4539 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4540 << SourceRange(TheCall->getArg(2)->getLocStart(),
4541 (*(TheCall->arg_end()-1))->getLocEnd());
4542
4543 ExprResult OrigArg0 = TheCall->getArg(0);
4544 ExprResult OrigArg1 = TheCall->getArg(1);
4545
4546 // Do standard promotions between the two arguments, returning their common
4547 // type.
4548 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4549 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4550 return true;
4551
4552 // Make sure any conversions are pushed back into the call; this is
4553 // type safe since unordered compare builtins are declared as "_Bool
4554 // foo(...)".
4555 TheCall->setArg(0, OrigArg0.get());
4556 TheCall->setArg(1, OrigArg1.get());
4557
4558 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4559 return false;
4560
4561 // If the common type isn't a real floating type, then the arguments were
4562 // invalid for this operation.
4563 if (Res.isNull() || !Res->isRealFloatingType())
4564 return Diag(OrigArg0.get()->getLocStart(),
4565 diag::err_typecheck_call_invalid_ordered_compare)
4566 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4567 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4568
4569 return false;
4570}
4571
4572/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4573/// __builtin_isnan and friends. This is declared to take (...), so we have
4574/// to check everything. We expect the last argument to be a floating point
4575/// value.
4576bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4577 if (TheCall->getNumArgs() < NumArgs)
4578 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4579 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4580 if (TheCall->getNumArgs() > NumArgs)
4581 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4582 diag::err_typecheck_call_too_many_args)
4583 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4584 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4585 (*(TheCall->arg_end()-1))->getLocEnd());
4586
4587 Expr *OrigArg = TheCall->getArg(NumArgs-1);
4588
4589 if (OrigArg->isTypeDependent())
4590 return false;
4591
4592 // This operation requires a non-_Complex floating-point number.
4593 if (!OrigArg->getType()->isRealFloatingType())
4594 return Diag(OrigArg->getLocStart(),
4595 diag::err_typecheck_call_invalid_unary_fp)
4596 << OrigArg->getType() << OrigArg->getSourceRange();
4597
4598 // If this is an implicit conversion from float -> float, double, or
4599 // long double, remove it.
4600 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4601 // Only remove standard FloatCasts, leaving other casts inplace
4602 if (Cast->getCastKind() == CK_FloatingCast) {
4603 Expr *CastArg = Cast->getSubExpr();
4604 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4605 assert(
4606 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4607 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
4608 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
4609 "promotion from float to either float, double, or long double is "
4610 "the only expected cast here");
4611 Cast->setSubExpr(nullptr);
4612 TheCall->setArg(NumArgs-1, CastArg);
4613 }
4614 }
4615 }
4616
4617 return false;
4618}
4619
4620// Customized Sema Checking for VSX builtins that have the following signature:
4621// vector [...] builtinName(vector [...], vector [...], const int);
4622// Which takes the same type of vectors (any legal vector type) for the first
4623// two arguments and takes compile time constant for the third argument.
4624// Example builtins are :
4625// vector double vec_xxpermdi(vector double, vector double, int);
4626// vector short vec_xxsldwi(vector short, vector short, int);
4627bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4628 unsigned ExpectedNumArgs = 3;
4629 if (TheCall->getNumArgs() < ExpectedNumArgs)
4630 return Diag(TheCall->getLocEnd(),
4631 diag::err_typecheck_call_too_few_args_at_least)
4632 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4633 << TheCall->getSourceRange();
4634
4635 if (TheCall->getNumArgs() > ExpectedNumArgs)
4636 return Diag(TheCall->getLocEnd(),
4637 diag::err_typecheck_call_too_many_args_at_most)
4638 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4639 << TheCall->getSourceRange();
4640
4641 // Check the third argument is a compile time constant
4642 llvm::APSInt Value;
4643 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4644 return Diag(TheCall->getLocStart(),
4645 diag::err_vsx_builtin_nonconstant_argument)
4646 << 3 /* argument index */ << TheCall->getDirectCallee()
4647 << SourceRange(TheCall->getArg(2)->getLocStart(),
4648 TheCall->getArg(2)->getLocEnd());
4649
4650 QualType Arg1Ty = TheCall->getArg(0)->getType();
4651 QualType Arg2Ty = TheCall->getArg(1)->getType();
4652
4653 // Check the type of argument 1 and argument 2 are vectors.
4654 SourceLocation BuiltinLoc = TheCall->getLocStart();
4655 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4656 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4657 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4658 << TheCall->getDirectCallee()
4659 << SourceRange(TheCall->getArg(0)->getLocStart(),
4660 TheCall->getArg(1)->getLocEnd());
4661 }
4662
4663 // Check the first two arguments are the same type.
4664 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4665 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4666 << TheCall->getDirectCallee()
4667 << SourceRange(TheCall->getArg(0)->getLocStart(),
4668 TheCall->getArg(1)->getLocEnd());
4669 }
4670
4671 // When default clang type checking is turned off and the customized type
4672 // checking is used, the returning type of the function must be explicitly
4673 // set. Otherwise it is _Bool by default.
4674 TheCall->setType(Arg1Ty);
4675
4676 return false;
4677}
4678
4679/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4680// This is declared to take (...), so we have to check everything.
4681ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4682 if (TheCall->getNumArgs() < 2)
4683 return ExprError(Diag(TheCall->getLocEnd(),
4684 diag::err_typecheck_call_too_few_args_at_least)
4685 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4686 << TheCall->getSourceRange());
4687
4688 // Determine which of the following types of shufflevector we're checking:
4689 // 1) unary, vector mask: (lhs, mask)
4690 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4691 QualType resType = TheCall->getArg(0)->getType();
4692 unsigned numElements = 0;
4693
4694 if (!TheCall->getArg(0)->isTypeDependent() &&
4695 !TheCall->getArg(1)->isTypeDependent()) {
4696 QualType LHSType = TheCall->getArg(0)->getType();
4697 QualType RHSType = TheCall->getArg(1)->getType();
4698
4699 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4700 return ExprError(Diag(TheCall->getLocStart(),
4701 diag::err_vec_builtin_non_vector)
4702 << TheCall->getDirectCallee()
4703 << SourceRange(TheCall->getArg(0)->getLocStart(),
4704 TheCall->getArg(1)->getLocEnd()));
4705
4706 numElements = LHSType->getAs<VectorType>()->getNumElements();
4707 unsigned numResElements = TheCall->getNumArgs() - 2;
4708
4709 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4710 // with mask. If so, verify that RHS is an integer vector type with the
4711 // same number of elts as lhs.
4712 if (TheCall->getNumArgs() == 2) {
4713 if (!RHSType->hasIntegerRepresentation() ||
4714 RHSType->getAs<VectorType>()->getNumElements() != numElements)
4715 return ExprError(Diag(TheCall->getLocStart(),
4716 diag::err_vec_builtin_incompatible_vector)
4717 << TheCall->getDirectCallee()
4718 << SourceRange(TheCall->getArg(1)->getLocStart(),
4719 TheCall->getArg(1)->getLocEnd()));
4720 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4721 return ExprError(Diag(TheCall->getLocStart(),
4722 diag::err_vec_builtin_incompatible_vector)
4723 << TheCall->getDirectCallee()
4724 << SourceRange(TheCall->getArg(0)->getLocStart(),
4725 TheCall->getArg(1)->getLocEnd()));
4726 } else if (numElements != numResElements) {
4727 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4728 resType = Context.getVectorType(eltType, numResElements,
4729 VectorType::GenericVector);
4730 }
4731 }
4732
4733 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4734 if (TheCall->getArg(i)->isTypeDependent() ||
4735 TheCall->getArg(i)->isValueDependent())
4736 continue;
4737
4738 llvm::APSInt Result(32);
4739 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4740 return ExprError(Diag(TheCall->getLocStart(),
4741 diag::err_shufflevector_nonconstant_argument)
4742 << TheCall->getArg(i)->getSourceRange());
4743
4744 // Allow -1 which will be translated to undef in the IR.
4745 if (Result.isSigned() && Result.isAllOnesValue())
4746 continue;
4747
4748 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4749 return ExprError(Diag(TheCall->getLocStart(),
4750 diag::err_shufflevector_argument_too_large)
4751 << TheCall->getArg(i)->getSourceRange());
4752 }
4753
4754 SmallVector<Expr*, 32> exprs;
4755
4756 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4757 exprs.push_back(TheCall->getArg(i));
4758 TheCall->setArg(i, nullptr);
4759 }
4760
4761 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4762 TheCall->getCallee()->getLocStart(),
4763 TheCall->getRParenLoc());
4764}
4765
4766/// SemaConvertVectorExpr - Handle __builtin_convertvector
4767ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4768 SourceLocation BuiltinLoc,
4769 SourceLocation RParenLoc) {
4770 ExprValueKind VK = VK_RValue;
4771 ExprObjectKind OK = OK_Ordinary;
4772 QualType DstTy = TInfo->getType();
4773 QualType SrcTy = E->getType();
4774
4775 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4776 return ExprError(Diag(BuiltinLoc,
4777 diag::err_convertvector_non_vector)
4778 << E->getSourceRange());
4779 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4780 return ExprError(Diag(BuiltinLoc,
4781 diag::err_convertvector_non_vector_type));
4782
4783 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4784 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4785 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4786 if (SrcElts != DstElts)
4787 return ExprError(Diag(BuiltinLoc,
4788 diag::err_convertvector_incompatible_vector)
4789 << E->getSourceRange());
4790 }
4791
4792 return new (Context)
4793 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4794}
4795
4796/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4797// This is declared to take (const void*, ...) and can take two
4798// optional constant int args.
4799bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4800 unsigned NumArgs = TheCall->getNumArgs();
4801
4802 if (NumArgs > 3)
4803 return Diag(TheCall->getLocEnd(),
4804 diag::err_typecheck_call_too_many_args_at_most)
4805 << 0 /*function call*/ << 3 << NumArgs
4806 << TheCall->getSourceRange();
4807
4808 // Argument 0 is checked for us and the remaining arguments must be
4809 // constant integers.
4810 for (unsigned i = 1; i != NumArgs; ++i)
Richard Sandiford28940af2014-04-16 08:47:51 +00004811 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004812 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004813
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004814 return false;
4815}
4816
Hal Finkelf0417332014-07-17 14:25:55 +00004817/// SemaBuiltinAssume - Handle __assume (MS Extension).
4818// __assume does not evaluate its arguments, and should warn if its argument
4819// has side effects.
4820bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4821 Expr *Arg = TheCall->getArg(0);
4822 if (Arg->isInstantiationDependent()) return false;
4823
4824 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004825 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004826 << Arg->getSourceRange()
4827 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4828
4829 return false;
4830}
4831
David Majnemer86b1bfa2016-10-31 18:07:57 +00004832/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004833/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4834/// than 8.
4835bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4836 // The alignment must be a constant integer.
4837 Expr *Arg = TheCall->getArg(1);
4838
4839 // We can't check the value of a dependent argument.
4840 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004841 if (const auto *UE =
4842 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4843 if (UE->getKind() == UETT_AlignOf)
4844 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4845 << Arg->getSourceRange();
4846
David Majnemer51169932016-10-31 05:37:48 +00004847 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4848
4849 if (!Result.isPowerOf2())
4850 return Diag(TheCall->getLocStart(),
4851 diag::err_alignment_not_power_of_two)
4852 << Arg->getSourceRange();
4853
4854 if (Result < Context.getCharWidth())
4855 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4856 << (unsigned)Context.getCharWidth()
4857 << Arg->getSourceRange();
4858
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004859 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004860 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004861 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004862 << Arg->getSourceRange();
4863 }
4864
4865 return false;
4866}
4867
4868/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004869/// as (const void*, size_t, ...) and can take one optional constant int arg.
4870bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4871 unsigned NumArgs = TheCall->getNumArgs();
4872
4873 if (NumArgs > 3)
4874 return Diag(TheCall->getLocEnd(),
4875 diag::err_typecheck_call_too_many_args_at_most)
4876 << 0 /*function call*/ << 3 << NumArgs
4877 << TheCall->getSourceRange();
4878
4879 // The alignment must be a constant integer.
4880 Expr *Arg = TheCall->getArg(1);
4881
4882 // We can't check the value of a dependent argument.
4883 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4884 llvm::APSInt Result;
4885 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4886 return true;
4887
4888 if (!Result.isPowerOf2())
4889 return Diag(TheCall->getLocStart(),
4890 diag::err_alignment_not_power_of_two)
4891 << Arg->getSourceRange();
4892 }
4893
4894 if (NumArgs > 2) {
4895 ExprResult Arg(TheCall->getArg(2));
4896 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4897 Context.getSizeType(), false);
4898 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4899 if (Arg.isInvalid()) return true;
4900 TheCall->setArg(2, Arg.get());
4901 }
Hal Finkelf0417332014-07-17 14:25:55 +00004902
4903 return false;
4904}
4905
Mehdi Amini06d367c2016-10-24 20:39:34 +00004906bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4907 unsigned BuiltinID =
4908 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4909 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4910
4911 unsigned NumArgs = TheCall->getNumArgs();
4912 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4913 if (NumArgs < NumRequiredArgs) {
4914 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4915 << 0 /* function call */ << NumRequiredArgs << NumArgs
4916 << TheCall->getSourceRange();
4917 }
4918 if (NumArgs >= NumRequiredArgs + 0x100) {
4919 return Diag(TheCall->getLocEnd(),
4920 diag::err_typecheck_call_too_many_args_at_most)
4921 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4922 << TheCall->getSourceRange();
4923 }
4924 unsigned i = 0;
4925
4926 // For formatting call, check buffer arg.
4927 if (!IsSizeCall) {
4928 ExprResult Arg(TheCall->getArg(i));
4929 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4930 Context, Context.VoidPtrTy, false);
4931 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4932 if (Arg.isInvalid())
4933 return true;
4934 TheCall->setArg(i, Arg.get());
4935 i++;
4936 }
4937
4938 // Check string literal arg.
4939 unsigned FormatIdx = i;
4940 {
4941 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4942 if (Arg.isInvalid())
4943 return true;
4944 TheCall->setArg(i, Arg.get());
4945 i++;
4946 }
4947
4948 // Make sure variadic args are scalar.
4949 unsigned FirstDataArg = i;
4950 while (i < NumArgs) {
4951 ExprResult Arg = DefaultVariadicArgumentPromotion(
4952 TheCall->getArg(i), VariadicFunction, nullptr);
4953 if (Arg.isInvalid())
4954 return true;
4955 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4956 if (ArgSize.getQuantity() >= 0x100) {
4957 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4958 << i << (int)ArgSize.getQuantity() << 0xff
4959 << TheCall->getSourceRange();
4960 }
4961 TheCall->setArg(i, Arg.get());
4962 i++;
4963 }
4964
4965 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4966 // call to avoid duplicate diagnostics.
4967 if (!IsSizeCall) {
4968 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4969 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4970 bool Success = CheckFormatArguments(
4971 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4972 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4973 CheckedVarArgs);
4974 if (!Success)
4975 return true;
4976 }
4977
4978 if (IsSizeCall) {
4979 TheCall->setType(Context.getSizeType());
4980 } else {
4981 TheCall->setType(Context.VoidPtrTy);
4982 }
4983 return false;
4984}
4985
Eric Christopher8d0c6212010-04-17 02:26:23 +00004986/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4987/// TheCall is a constant expression.
4988bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4989 llvm::APSInt &Result) {
4990 Expr *Arg = TheCall->getArg(ArgNum);
4991 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4992 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4993
4994 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4995
4996 if (!Arg->isIntegerConstantExpr(Result, Context))
4997 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004998 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004999
Chris Lattnerd545ad12009-09-23 06:06:36 +00005000 return false;
5001}
5002
Richard Sandiford28940af2014-04-16 08:47:51 +00005003/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5004/// TheCall is a constant expression in the range [Low, High].
5005bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5006 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00005007 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005008
5009 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00005010 Expr *Arg = TheCall->getArg(ArgNum);
5011 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005012 return false;
5013
Eric Christopher8d0c6212010-04-17 02:26:23 +00005014 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00005015 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005016 return true;
5017
Richard Sandiford28940af2014-04-16 08:47:51 +00005018 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00005019 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00005020 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00005021
5022 return false;
5023}
5024
Simon Dardis1f90f2d2016-10-19 17:50:52 +00005025/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5026/// TheCall is a constant expression is a multiple of Num..
5027bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5028 unsigned Num) {
5029 llvm::APSInt Result;
5030
5031 // We can't check the value of a dependent argument.
5032 Expr *Arg = TheCall->getArg(ArgNum);
5033 if (Arg->isTypeDependent() || Arg->isValueDependent())
5034 return false;
5035
5036 // Check constant-ness first.
5037 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5038 return true;
5039
5040 if (Result.getSExtValue() % Num != 0)
5041 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
5042 << Num << Arg->getSourceRange();
5043
5044 return false;
5045}
5046
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005047/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5048/// TheCall is an ARM/AArch64 special register string literal.
5049bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5050 int ArgNum, unsigned ExpectedFieldNum,
5051 bool AllowName) {
5052 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5053 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5054 BuiltinID == ARM::BI__builtin_arm_rsr ||
5055 BuiltinID == ARM::BI__builtin_arm_rsrp ||
5056 BuiltinID == ARM::BI__builtin_arm_wsr ||
5057 BuiltinID == ARM::BI__builtin_arm_wsrp;
5058 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5059 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5060 BuiltinID == AArch64::BI__builtin_arm_rsr ||
5061 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5062 BuiltinID == AArch64::BI__builtin_arm_wsr ||
5063 BuiltinID == AArch64::BI__builtin_arm_wsrp;
5064 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5065
5066 // We can't check the value of a dependent argument.
5067 Expr *Arg = TheCall->getArg(ArgNum);
5068 if (Arg->isTypeDependent() || Arg->isValueDependent())
5069 return false;
5070
5071 // Check if the argument is a string literal.
5072 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5073 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
5074 << Arg->getSourceRange();
5075
5076 // Check the type of special register given.
5077 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5078 SmallVector<StringRef, 6> Fields;
5079 Reg.split(Fields, ":");
5080
5081 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5082 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5083 << Arg->getSourceRange();
5084
5085 // If the string is the name of a register then we cannot check that it is
5086 // valid here but if the string is of one the forms described in ACLE then we
5087 // can check that the supplied fields are integers and within the valid
5088 // ranges.
5089 if (Fields.size() > 1) {
5090 bool FiveFields = Fields.size() == 5;
5091
5092 bool ValidString = true;
5093 if (IsARMBuiltin) {
5094 ValidString &= Fields[0].startswith_lower("cp") ||
5095 Fields[0].startswith_lower("p");
5096 if (ValidString)
5097 Fields[0] =
5098 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5099
5100 ValidString &= Fields[2].startswith_lower("c");
5101 if (ValidString)
5102 Fields[2] = Fields[2].drop_front(1);
5103
5104 if (FiveFields) {
5105 ValidString &= Fields[3].startswith_lower("c");
5106 if (ValidString)
5107 Fields[3] = Fields[3].drop_front(1);
5108 }
5109 }
5110
5111 SmallVector<int, 5> Ranges;
5112 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00005113 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005114 else
5115 Ranges.append({15, 7, 15});
5116
5117 for (unsigned i=0; i<Fields.size(); ++i) {
5118 int IntField;
5119 ValidString &= !Fields[i].getAsInteger(10, IntField);
5120 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5121 }
5122
5123 if (!ValidString)
5124 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5125 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005126 } else if (IsAArch64Builtin && Fields.size() == 1) {
5127 // If the register name is one of those that appear in the condition below
5128 // and the special register builtin being used is one of the write builtins,
5129 // then we require that the argument provided for writing to the register
5130 // is an integer constant expression. This is because it will be lowered to
5131 // an MSR (immediate) instruction, so we need to know the immediate at
5132 // compile time.
5133 if (TheCall->getNumArgs() != 2)
5134 return false;
5135
5136 std::string RegLower = Reg.lower();
5137 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5138 RegLower != "pan" && RegLower != "uao")
5139 return false;
5140
5141 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5142 }
5143
5144 return false;
5145}
5146
Eli Friedmanc97d0142009-05-03 06:04:26 +00005147/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005148/// This checks that the target supports __builtin_longjmp and
5149/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005150bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005151 if (!Context.getTargetInfo().hasSjLjLowering())
5152 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5153 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5154
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005155 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00005156 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00005157
Eric Christopher8d0c6212010-04-17 02:26:23 +00005158 // TODO: This is less than ideal. Overload this to take a value.
5159 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5160 return true;
5161
5162 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005163 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5164 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5165
5166 return false;
5167}
5168
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005169/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5170/// This checks that the target supports __builtin_setjmp.
5171bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5172 if (!Context.getTargetInfo().hasSjLjLowering())
5173 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5174 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5175 return false;
5176}
5177
Richard Smithd7293d72013-08-05 18:49:43 +00005178namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005179
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005180class UncoveredArgHandler {
5181 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005182
5183 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005184 SmallVector<const Expr *, 4> DiagnosticExprs;
5185
5186public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005187 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005188
5189 bool hasUncoveredArg() const {
5190 return (FirstUncoveredArg >= 0);
5191 }
5192
5193 unsigned getUncoveredArg() const {
5194 assert(hasUncoveredArg() && "no uncovered argument");
5195 return FirstUncoveredArg;
5196 }
5197
5198 void setAllCovered() {
5199 // A string has been found with all arguments covered, so clear out
5200 // the diagnostics.
5201 DiagnosticExprs.clear();
5202 FirstUncoveredArg = AllCovered;
5203 }
5204
5205 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5206 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5207
5208 // Don't update if a previous string covers all arguments.
5209 if (FirstUncoveredArg == AllCovered)
5210 return;
5211
5212 // UncoveredArgHandler tracks the highest uncovered argument index
5213 // and with it all the strings that match this index.
5214 if (NewFirstUncoveredArg == FirstUncoveredArg)
5215 DiagnosticExprs.push_back(StrExpr);
5216 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5217 DiagnosticExprs.clear();
5218 DiagnosticExprs.push_back(StrExpr);
5219 FirstUncoveredArg = NewFirstUncoveredArg;
5220 }
5221 }
5222
5223 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5224};
5225
Richard Smithd7293d72013-08-05 18:49:43 +00005226enum StringLiteralCheckType {
5227 SLCT_NotALiteral,
5228 SLCT_UncheckedLiteral,
5229 SLCT_CheckedLiteral
5230};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005231
5232} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005233
Stephen Hines648c3692016-09-16 01:07:04 +00005234static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5235 BinaryOperatorKind BinOpKind,
5236 bool AddendIsRight) {
5237 unsigned BitWidth = Offset.getBitWidth();
5238 unsigned AddendBitWidth = Addend.getBitWidth();
5239 // There might be negative interim results.
5240 if (Addend.isUnsigned()) {
5241 Addend = Addend.zext(++AddendBitWidth);
5242 Addend.setIsSigned(true);
5243 }
5244 // Adjust the bit width of the APSInts.
5245 if (AddendBitWidth > BitWidth) {
5246 Offset = Offset.sext(AddendBitWidth);
5247 BitWidth = AddendBitWidth;
5248 } else if (BitWidth > AddendBitWidth) {
5249 Addend = Addend.sext(BitWidth);
5250 }
5251
5252 bool Ov = false;
5253 llvm::APSInt ResOffset = Offset;
5254 if (BinOpKind == BO_Add)
5255 ResOffset = Offset.sadd_ov(Addend, Ov);
5256 else {
5257 assert(AddendIsRight && BinOpKind == BO_Sub &&
5258 "operator must be add or sub with addend on the right");
5259 ResOffset = Offset.ssub_ov(Addend, Ov);
5260 }
5261
5262 // We add an offset to a pointer here so we should support an offset as big as
5263 // possible.
5264 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005265 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5266 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005267 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005268 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5269 return;
5270 }
5271
5272 Offset = ResOffset;
5273}
5274
5275namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005276
Stephen Hines648c3692016-09-16 01:07:04 +00005277// This is a wrapper class around StringLiteral to support offsetted string
5278// literals as format strings. It takes the offset into account when returning
5279// the string and its length or the source locations to display notes correctly.
5280class FormatStringLiteral {
5281 const StringLiteral *FExpr;
5282 int64_t Offset;
5283
5284 public:
5285 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5286 : FExpr(fexpr), Offset(Offset) {}
5287
5288 StringRef getString() const {
5289 return FExpr->getString().drop_front(Offset);
5290 }
5291
5292 unsigned getByteLength() const {
5293 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5294 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005295
Stephen Hines648c3692016-09-16 01:07:04 +00005296 unsigned getLength() const { return FExpr->getLength() - Offset; }
5297 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5298
5299 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5300
5301 QualType getType() const { return FExpr->getType(); }
5302
5303 bool isAscii() const { return FExpr->isAscii(); }
5304 bool isWide() const { return FExpr->isWide(); }
5305 bool isUTF8() const { return FExpr->isUTF8(); }
5306 bool isUTF16() const { return FExpr->isUTF16(); }
5307 bool isUTF32() const { return FExpr->isUTF32(); }
5308 bool isPascal() const { return FExpr->isPascal(); }
5309
5310 SourceLocation getLocationOfByte(
5311 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5312 const TargetInfo &Target, unsigned *StartToken = nullptr,
5313 unsigned *StartTokenByteOffset = nullptr) const {
5314 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5315 StartToken, StartTokenByteOffset);
5316 }
5317
5318 SourceLocation getLocStart() const LLVM_READONLY {
5319 return FExpr->getLocStart().getLocWithOffset(Offset);
5320 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005321
Stephen Hines648c3692016-09-16 01:07:04 +00005322 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5323};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005324
5325} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005326
5327static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005328 const Expr *OrigFormatExpr,
5329 ArrayRef<const Expr *> Args,
5330 bool HasVAListArg, unsigned format_idx,
5331 unsigned firstDataArg,
5332 Sema::FormatStringType Type,
5333 bool inFunctionCall,
5334 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005335 llvm::SmallBitVector &CheckedVarArgs,
5336 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005337
Richard Smith55ce3522012-06-25 20:30:08 +00005338// Determine if an expression is a string literal or constant string.
5339// If this function returns false on the arguments to a function expecting a
5340// format string, we will usually need to emit a warning.
5341// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005342static StringLiteralCheckType
5343checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5344 bool HasVAListArg, unsigned format_idx,
5345 unsigned firstDataArg, Sema::FormatStringType Type,
5346 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005347 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005348 UncoveredArgHandler &UncoveredArg,
5349 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005350 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005351 assert(Offset.isSigned() && "invalid offset");
5352
Douglas Gregorc25f7662009-05-19 22:10:17 +00005353 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005354 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005355
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005356 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005357
Richard Smithd7293d72013-08-05 18:49:43 +00005358 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005359 // Technically -Wformat-nonliteral does not warn about this case.
5360 // The behavior of printf and friends in this case is implementation
5361 // dependent. Ideally if the format string cannot be null then
5362 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005363 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005364
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005365 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005366 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005367 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005368 // The expression is a literal if both sub-expressions were, and it was
5369 // completely checked only if both sub-expressions were checked.
5370 const AbstractConditionalOperator *C =
5371 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005372
5373 // Determine whether it is necessary to check both sub-expressions, for
5374 // example, because the condition expression is a constant that can be
5375 // evaluated at compile time.
5376 bool CheckLeft = true, CheckRight = true;
5377
5378 bool Cond;
5379 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5380 if (Cond)
5381 CheckRight = false;
5382 else
5383 CheckLeft = false;
5384 }
5385
Stephen Hines648c3692016-09-16 01:07:04 +00005386 // We need to maintain the offsets for the right and the left hand side
5387 // separately to check if every possible indexed expression is a valid
5388 // string literal. They might have different offsets for different string
5389 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005390 StringLiteralCheckType Left;
5391 if (!CheckLeft)
5392 Left = SLCT_UncheckedLiteral;
5393 else {
5394 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5395 HasVAListArg, format_idx, firstDataArg,
5396 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005397 CheckedVarArgs, UncoveredArg, Offset);
5398 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005399 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005400 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005401 }
5402
Richard Smith55ce3522012-06-25 20:30:08 +00005403 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005404 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005405 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005406 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005407 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005408
5409 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005410 }
5411
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005412 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005413 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5414 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005415
John McCallc07a0c72011-02-17 10:25:35 +00005416 case Stmt::OpaqueValueExprClass:
5417 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5418 E = src;
5419 goto tryAgain;
5420 }
Richard Smith55ce3522012-06-25 20:30:08 +00005421 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005422
Ted Kremeneka8890832011-02-24 23:03:04 +00005423 case Stmt::PredefinedExprClass:
5424 // While __func__, etc., are technically not string literals, they
5425 // cannot contain format specifiers and thus are not a security
5426 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005427 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005428
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005429 case Stmt::DeclRefExprClass: {
5430 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005431
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005432 // As an exception, do not flag errors for variables binding to
5433 // const string literals.
5434 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5435 bool isConstant = false;
5436 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005437
Richard Smithd7293d72013-08-05 18:49:43 +00005438 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5439 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005440 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005441 isConstant = T.isConstant(S.Context) &&
5442 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005443 } else if (T->isObjCObjectPointerType()) {
5444 // In ObjC, there is usually no "const ObjectPointer" type,
5445 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005446 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005447 }
Mike Stump11289f42009-09-09 15:08:12 +00005448
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005449 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005450 if (const Expr *Init = VD->getAnyInitializer()) {
5451 // Look through initializers like const char c[] = { "foo" }
5452 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5453 if (InitList->isStringLiteralInit())
5454 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5455 }
Richard Smithd7293d72013-08-05 18:49:43 +00005456 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005457 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005458 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005459 /*InFunctionCall*/ false, CheckedVarArgs,
5460 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005461 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005462 }
Mike Stump11289f42009-09-09 15:08:12 +00005463
Anders Carlssonb012ca92009-06-28 19:55:58 +00005464 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5465 // special check to see if the format string is a function parameter
5466 // of the function calling the printf function. If the function
5467 // has an attribute indicating it is a printf-like function, then we
5468 // should suppress warnings concerning non-literals being used in a call
5469 // to a vprintf function. For example:
5470 //
5471 // void
5472 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5473 // va_list ap;
5474 // va_start(ap, fmt);
5475 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5476 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005477 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005478 if (HasVAListArg) {
5479 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5480 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5481 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005482 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005483 // adjust for implicit parameter
5484 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5485 if (MD->isInstance())
5486 ++PVIndex;
5487 // We also check if the formats are compatible.
5488 // We can't pass a 'scanf' string to a 'printf' function.
5489 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005490 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005491 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005492 }
5493 }
5494 }
5495 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005496 }
Mike Stump11289f42009-09-09 15:08:12 +00005497
Richard Smith55ce3522012-06-25 20:30:08 +00005498 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005499 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005500
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005501 case Stmt::CallExprClass:
5502 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005503 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005504 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5505 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005506 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005507 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005508 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005509 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005510 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005511 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5512 unsigned BuiltinID = FD->getBuiltinID();
5513 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5514 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5515 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005516 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005517 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005518 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005519 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005520 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005521 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005522 }
5523 }
Mike Stump11289f42009-09-09 15:08:12 +00005524
Richard Smith55ce3522012-06-25 20:30:08 +00005525 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005526 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005527 case Stmt::ObjCMessageExprClass: {
5528 const auto *ME = cast<ObjCMessageExpr>(E);
5529 if (const auto *ND = ME->getMethodDecl()) {
5530 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005531 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005532 return checkFormatStringExpr(
5533 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5534 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5535 }
5536 }
5537
5538 return SLCT_NotALiteral;
5539 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005540 case Stmt::ObjCStringLiteralClass:
5541 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005542 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005543
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005544 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005545 StrE = ObjCFExpr->getString();
5546 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005547 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005548
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005549 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005550 if (Offset.isNegative() || Offset > StrE->getLength()) {
5551 // TODO: It would be better to have an explicit warning for out of
5552 // bounds literals.
5553 return SLCT_NotALiteral;
5554 }
5555 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5556 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005557 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005558 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005559 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005560 }
Mike Stump11289f42009-09-09 15:08:12 +00005561
Richard Smith55ce3522012-06-25 20:30:08 +00005562 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005563 }
Stephen Hines648c3692016-09-16 01:07:04 +00005564 case Stmt::BinaryOperatorClass: {
5565 llvm::APSInt LResult;
5566 llvm::APSInt RResult;
5567
5568 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5569
5570 // A string literal + an int offset is still a string literal.
5571 if (BinOp->isAdditiveOp()) {
5572 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5573 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5574
5575 if (LIsInt != RIsInt) {
5576 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5577
5578 if (LIsInt) {
5579 if (BinOpKind == BO_Add) {
5580 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5581 E = BinOp->getRHS();
5582 goto tryAgain;
5583 }
5584 } else {
5585 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5586 E = BinOp->getLHS();
5587 goto tryAgain;
5588 }
5589 }
Stephen Hines648c3692016-09-16 01:07:04 +00005590 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005591
5592 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005593 }
5594 case Stmt::UnaryOperatorClass: {
5595 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5596 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005597 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005598 llvm::APSInt IndexResult;
5599 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5600 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5601 E = ASE->getBase();
5602 goto tryAgain;
5603 }
5604 }
5605
5606 return SLCT_NotALiteral;
5607 }
Mike Stump11289f42009-09-09 15:08:12 +00005608
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005609 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005610 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005611 }
5612}
5613
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005614Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005615 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005616 .Case("scanf", FST_Scanf)
5617 .Cases("printf", "printf0", FST_Printf)
5618 .Cases("NSString", "CFString", FST_NSString)
5619 .Case("strftime", FST_Strftime)
5620 .Case("strfmon", FST_Strfmon)
5621 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5622 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5623 .Case("os_trace", FST_OSLog)
5624 .Case("os_log", FST_OSLog)
5625 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005626}
5627
Jordan Rose3e0ec582012-07-19 18:10:23 +00005628/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005629/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005630/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005631bool Sema::CheckFormatArguments(const FormatAttr *Format,
5632 ArrayRef<const Expr *> Args,
5633 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005634 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005635 SourceLocation Loc, SourceRange Range,
5636 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005637 FormatStringInfo FSI;
5638 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005639 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005640 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005641 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005642 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005643}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005644
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005645bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005646 bool HasVAListArg, unsigned format_idx,
5647 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005648 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005649 SourceLocation Loc, SourceRange Range,
5650 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005651 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005652 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005653 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005654 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005655 }
Mike Stump11289f42009-09-09 15:08:12 +00005656
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005657 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005658
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005659 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005660 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005661 // Dynamically generated format strings are difficult to
5662 // automatically vet at compile time. Requiring that format strings
5663 // are string literals: (1) permits the checking of format strings by
5664 // the compiler and thereby (2) can practically remove the source of
5665 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005666
Mike Stump11289f42009-09-09 15:08:12 +00005667 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005668 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005669 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005670 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005671 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005672 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005673 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5674 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005675 /*IsFunctionCall*/ true, CheckedVarArgs,
5676 UncoveredArg,
5677 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005678
5679 // Generate a diagnostic where an uncovered argument is detected.
5680 if (UncoveredArg.hasUncoveredArg()) {
5681 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5682 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5683 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5684 }
5685
Richard Smith55ce3522012-06-25 20:30:08 +00005686 if (CT != SLCT_NotALiteral)
5687 // Literal format string found, check done!
5688 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005689
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005690 // Strftime is particular as it always uses a single 'time' argument,
5691 // so it is safe to pass a non-literal string.
5692 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005693 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005694
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005695 // Do not emit diag when the string param is a macro expansion and the
5696 // format is either NSString or CFString. This is a hack to prevent
5697 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5698 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005699 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5700 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005701 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005702
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005703 // If there are no arguments specified, warn with -Wformat-security, otherwise
5704 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005705 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005706 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5707 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005708 switch (Type) {
5709 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005710 break;
5711 case FST_Kprintf:
5712 case FST_FreeBSDKPrintf:
5713 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005714 Diag(FormatLoc, diag::note_format_security_fixit)
5715 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005716 break;
5717 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005718 Diag(FormatLoc, diag::note_format_security_fixit)
5719 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005720 break;
5721 }
5722 } else {
5723 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005724 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005725 }
Richard Smith55ce3522012-06-25 20:30:08 +00005726 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005727}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005728
Ted Kremenekab278de2010-01-28 23:39:18 +00005729namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005730
Ted Kremenek02087932010-07-16 02:11:22 +00005731class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5732protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005733 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005734 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005735 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005736 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005737 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005738 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005739 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005740 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005741 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005742 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005743 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005744 bool usesPositionalArgs = false;
5745 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005746 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005747 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005748 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005749 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005750
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005751public:
Stephen Hines648c3692016-09-16 01:07:04 +00005752 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005753 const Expr *origFormatExpr,
5754 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005755 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005756 ArrayRef<const Expr *> Args, unsigned formatIdx,
5757 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005758 llvm::SmallBitVector &CheckedVarArgs,
5759 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005760 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5761 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5762 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005763 inFunctionCall(inFunctionCall), CallType(callType),
5764 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005765 CoveredArgs.resize(numDataArgs);
5766 CoveredArgs.reset();
5767 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005768
Ted Kremenek019d2242010-01-29 01:50:07 +00005769 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005770
Ted Kremenek02087932010-07-16 02:11:22 +00005771 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005772 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005773
Jordan Rose92303592012-09-08 04:00:03 +00005774 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005775 const analyze_format_string::FormatSpecifier &FS,
5776 const analyze_format_string::ConversionSpecifier &CS,
5777 const char *startSpecifier, unsigned specifierLen,
5778 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005779
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005780 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005781 const analyze_format_string::FormatSpecifier &FS,
5782 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005783
5784 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005785 const analyze_format_string::ConversionSpecifier &CS,
5786 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005787
Craig Toppere14c0f82014-03-12 04:55:44 +00005788 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005789
Craig Toppere14c0f82014-03-12 04:55:44 +00005790 void HandleInvalidPosition(const char *startSpecifier,
5791 unsigned specifierLen,
5792 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005793
Craig Toppere14c0f82014-03-12 04:55:44 +00005794 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005795
Craig Toppere14c0f82014-03-12 04:55:44 +00005796 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005797
Richard Trieu03cf7b72011-10-28 00:41:25 +00005798 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005799 static void
5800 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5801 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5802 bool IsStringLocation, Range StringRange,
5803 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005804
Ted Kremenek02087932010-07-16 02:11:22 +00005805protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005806 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5807 const char *startSpec,
5808 unsigned specifierLen,
5809 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005810
5811 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5812 const char *startSpec,
5813 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005814
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005815 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005816 CharSourceRange getSpecifierRange(const char *startSpecifier,
5817 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005818 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005819
Ted Kremenek5739de72010-01-29 01:06:55 +00005820 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005821
5822 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5823 const analyze_format_string::ConversionSpecifier &CS,
5824 const char *startSpecifier, unsigned specifierLen,
5825 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005826
5827 template <typename Range>
5828 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5829 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005830 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005831};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005832
5833} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005834
Ted Kremenek02087932010-07-16 02:11:22 +00005835SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005836 return OrigFormatExpr->getSourceRange();
5837}
5838
Ted Kremenek02087932010-07-16 02:11:22 +00005839CharSourceRange CheckFormatHandler::
5840getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005841 SourceLocation Start = getLocationOfByte(startSpecifier);
5842 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5843
5844 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005845 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005846
5847 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005848}
5849
Ted Kremenek02087932010-07-16 02:11:22 +00005850SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005851 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5852 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005853}
5854
Ted Kremenek02087932010-07-16 02:11:22 +00005855void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5856 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005857 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5858 getLocationOfByte(startSpecifier),
5859 /*IsStringLocation*/true,
5860 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005861}
5862
Jordan Rose92303592012-09-08 04:00:03 +00005863void CheckFormatHandler::HandleInvalidLengthModifier(
5864 const analyze_format_string::FormatSpecifier &FS,
5865 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005866 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005867 using namespace analyze_format_string;
5868
5869 const LengthModifier &LM = FS.getLengthModifier();
5870 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5871
5872 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005873 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005874 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005875 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005876 getLocationOfByte(LM.getStart()),
5877 /*IsStringLocation*/true,
5878 getSpecifierRange(startSpecifier, specifierLen));
5879
5880 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5881 << FixedLM->toString()
5882 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5883
5884 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005885 FixItHint Hint;
5886 if (DiagID == diag::warn_format_nonsensical_length)
5887 Hint = FixItHint::CreateRemoval(LMRange);
5888
5889 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005890 getLocationOfByte(LM.getStart()),
5891 /*IsStringLocation*/true,
5892 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005893 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005894 }
5895}
5896
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005897void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005898 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005899 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005900 using namespace analyze_format_string;
5901
5902 const LengthModifier &LM = FS.getLengthModifier();
5903 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5904
5905 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005906 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005907 if (FixedLM) {
5908 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5909 << LM.toString() << 0,
5910 getLocationOfByte(LM.getStart()),
5911 /*IsStringLocation*/true,
5912 getSpecifierRange(startSpecifier, specifierLen));
5913
5914 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5915 << FixedLM->toString()
5916 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5917
5918 } else {
5919 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5920 << LM.toString() << 0,
5921 getLocationOfByte(LM.getStart()),
5922 /*IsStringLocation*/true,
5923 getSpecifierRange(startSpecifier, specifierLen));
5924 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005925}
5926
5927void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5928 const analyze_format_string::ConversionSpecifier &CS,
5929 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005930 using namespace analyze_format_string;
5931
5932 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005933 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005934 if (FixedCS) {
5935 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5936 << CS.toString() << /*conversion specifier*/1,
5937 getLocationOfByte(CS.getStart()),
5938 /*IsStringLocation*/true,
5939 getSpecifierRange(startSpecifier, specifierLen));
5940
5941 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5942 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5943 << FixedCS->toString()
5944 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5945 } else {
5946 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5947 << CS.toString() << /*conversion specifier*/1,
5948 getLocationOfByte(CS.getStart()),
5949 /*IsStringLocation*/true,
5950 getSpecifierRange(startSpecifier, specifierLen));
5951 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005952}
5953
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005954void CheckFormatHandler::HandlePosition(const char *startPos,
5955 unsigned posLen) {
5956 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5957 getLocationOfByte(startPos),
5958 /*IsStringLocation*/true,
5959 getSpecifierRange(startPos, posLen));
5960}
5961
Ted Kremenekd1668192010-02-27 01:41:03 +00005962void
Ted Kremenek02087932010-07-16 02:11:22 +00005963CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5964 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005965 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5966 << (unsigned) p,
5967 getLocationOfByte(startPos), /*IsStringLocation*/true,
5968 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005969}
5970
Ted Kremenek02087932010-07-16 02:11:22 +00005971void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005972 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005973 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5974 getLocationOfByte(startPos),
5975 /*IsStringLocation*/true,
5976 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005977}
5978
Ted Kremenek02087932010-07-16 02:11:22 +00005979void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005980 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005981 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005982 EmitFormatDiagnostic(
5983 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5984 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5985 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005986 }
Ted Kremenek02087932010-07-16 02:11:22 +00005987}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005988
Jordan Rose58bbe422012-07-19 18:10:08 +00005989// Note that this may return NULL if there was an error parsing or building
5990// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005991const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005992 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005993}
5994
5995void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005996 // Does the number of data arguments exceed the number of
5997 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005998 if (!HasVAListArg) {
5999 // Find any arguments that weren't covered.
6000 CoveredArgs.flip();
6001 signed notCoveredArg = CoveredArgs.find_first();
6002 if (notCoveredArg >= 0) {
6003 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006004 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6005 } else {
6006 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00006007 }
6008 }
6009}
6010
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006011void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6012 const Expr *ArgExpr) {
6013 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6014 "Invalid state");
6015
6016 if (!ArgExpr)
6017 return;
6018
6019 SourceLocation Loc = ArgExpr->getLocStart();
6020
6021 if (S.getSourceManager().isInSystemMacro(Loc))
6022 return;
6023
6024 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6025 for (auto E : DiagnosticExprs)
6026 PDiag << E->getSourceRange();
6027
6028 CheckFormatHandler::EmitFormatDiagnostic(
6029 S, IsFunctionCall, DiagnosticExprs[0],
6030 PDiag, Loc, /*IsStringLocation*/false,
6031 DiagnosticExprs[0]->getSourceRange());
6032}
6033
Ted Kremenekce815422010-07-19 21:25:57 +00006034bool
6035CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6036 SourceLocation Loc,
6037 const char *startSpec,
6038 unsigned specifierLen,
6039 const char *csStart,
6040 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00006041 bool keepGoing = true;
6042 if (argIndex < NumDataArgs) {
6043 // Consider the argument coverered, even though the specifier doesn't
6044 // make sense.
6045 CoveredArgs.set(argIndex);
6046 }
6047 else {
6048 // If argIndex exceeds the number of data arguments we
6049 // don't issue a warning because that is just a cascade of warnings (and
6050 // they may have intended '%%' anyway). We don't want to continue processing
6051 // the format string after this point, however, as we will like just get
6052 // gibberish when trying to match arguments.
6053 keepGoing = false;
6054 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006055
6056 StringRef Specifier(csStart, csLen);
6057
6058 // If the specifier in non-printable, it could be the first byte of a UTF-8
6059 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6060 // hex value.
6061 std::string CodePointStr;
6062 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00006063 llvm::UTF32 CodePoint;
6064 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6065 const llvm::UTF8 *E =
6066 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6067 llvm::ConversionResult Result =
6068 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006069
Justin Lebar90910552016-09-30 00:38:45 +00006070 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006071 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00006072 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006073 }
6074
6075 llvm::raw_string_ostream OS(CodePointStr);
6076 if (CodePoint < 256)
6077 OS << "\\x" << llvm::format("%02x", CodePoint);
6078 else if (CodePoint <= 0xFFFF)
6079 OS << "\\u" << llvm::format("%04x", CodePoint);
6080 else
6081 OS << "\\U" << llvm::format("%08x", CodePoint);
6082 OS.flush();
6083 Specifier = CodePointStr;
6084 }
6085
6086 EmitFormatDiagnostic(
6087 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6088 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6089
Ted Kremenekce815422010-07-19 21:25:57 +00006090 return keepGoing;
6091}
6092
Richard Trieu03cf7b72011-10-28 00:41:25 +00006093void
6094CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6095 const char *startSpec,
6096 unsigned specifierLen) {
6097 EmitFormatDiagnostic(
6098 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6099 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6100}
6101
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006102bool
6103CheckFormatHandler::CheckNumArgs(
6104 const analyze_format_string::FormatSpecifier &FS,
6105 const analyze_format_string::ConversionSpecifier &CS,
6106 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6107
6108 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006109 PartialDiagnostic PDiag = FS.usesPositionalArg()
6110 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6111 << (argIndex+1) << NumDataArgs)
6112 : S.PDiag(diag::warn_printf_insufficient_data_args);
6113 EmitFormatDiagnostic(
6114 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6115 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006116
6117 // Since more arguments than conversion tokens are given, by extension
6118 // all arguments are covered, so mark this as so.
6119 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006120 return false;
6121 }
6122 return true;
6123}
6124
Richard Trieu03cf7b72011-10-28 00:41:25 +00006125template<typename Range>
6126void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6127 SourceLocation Loc,
6128 bool IsStringLocation,
6129 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00006130 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006131 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00006132 Loc, IsStringLocation, StringRange, FixIt);
6133}
6134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006135/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00006136/// so that the function call and string are in diagnostic messages.
6137///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006138/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00006139/// call and only one diagnostic message will be produced. Otherwise, an
6140/// extra note will be emitted pointing to location of the format string.
6141///
6142/// \param ArgumentExpr the expression that is passed as the format string
6143/// argument in the function call. Used for getting locations when two
6144/// diagnostics are emitted.
6145///
6146/// \param PDiag the callee should already have provided any strings for the
6147/// diagnostic message. This function only adds locations and fixits
6148/// to diagnostics.
6149///
6150/// \param Loc primary location for diagnostic. If two diagnostics are
6151/// required, one will be at Loc and a new SourceLocation will be created for
6152/// the other one.
6153///
6154/// \param IsStringLocation if true, Loc points to the format string should be
6155/// used for the note. Otherwise, Loc points to the argument list and will
6156/// be used with PDiag.
6157///
6158/// \param StringRange some or all of the string to highlight. This is
6159/// templated so it can accept either a CharSourceRange or a SourceRange.
6160///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006161/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00006162template <typename Range>
6163void CheckFormatHandler::EmitFormatDiagnostic(
6164 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6165 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6166 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00006167 if (InFunctionCall) {
6168 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6169 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006170 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006171 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006172 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6173 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006174
6175 const Sema::SemaDiagnosticBuilder &Note =
6176 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6177 diag::note_format_string_defined);
6178
6179 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006180 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006181 }
6182}
6183
Ted Kremenek02087932010-07-16 02:11:22 +00006184//===--- CHECK: Printf format string checking ------------------------------===//
6185
6186namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006187
Ted Kremenek02087932010-07-16 02:11:22 +00006188class CheckPrintfHandler : public CheckFormatHandler {
6189public:
Stephen Hines648c3692016-09-16 01:07:04 +00006190 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006191 const Expr *origFormatExpr,
6192 const Sema::FormatStringType type, unsigned firstDataArg,
6193 unsigned numDataArgs, bool isObjC, const char *beg,
6194 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006195 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006196 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006197 llvm::SmallBitVector &CheckedVarArgs,
6198 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006199 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6200 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6201 inFunctionCall, CallType, CheckedVarArgs,
6202 UncoveredArg) {}
6203
6204 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6205
6206 /// Returns true if '%@' specifiers are allowed in the format string.
6207 bool allowsObjCArg() const {
6208 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6209 FSType == Sema::FST_OSTrace;
6210 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006211
Ted Kremenek02087932010-07-16 02:11:22 +00006212 bool HandleInvalidPrintfConversionSpecifier(
6213 const analyze_printf::PrintfSpecifier &FS,
6214 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006215 unsigned specifierLen) override;
6216
Ted Kremenek02087932010-07-16 02:11:22 +00006217 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6218 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006219 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006220 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6221 const char *StartSpecifier,
6222 unsigned SpecifierLen,
6223 const Expr *E);
6224
Ted Kremenek02087932010-07-16 02:11:22 +00006225 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6226 const char *startSpecifier, unsigned specifierLen);
6227 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6228 const analyze_printf::OptionalAmount &Amt,
6229 unsigned type,
6230 const char *startSpecifier, unsigned specifierLen);
6231 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6232 const analyze_printf::OptionalFlag &flag,
6233 const char *startSpecifier, unsigned specifierLen);
6234 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6235 const analyze_printf::OptionalFlag &ignoredFlag,
6236 const analyze_printf::OptionalFlag &flag,
6237 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006238 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006239 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006240
6241 void HandleEmptyObjCModifierFlag(const char *startFlag,
6242 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006243
Ted Kremenek2b417712015-07-02 05:39:16 +00006244 void HandleInvalidObjCModifierFlag(const char *startFlag,
6245 unsigned flagLen) override;
6246
6247 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6248 const char *flagsEnd,
6249 const char *conversionPosition)
6250 override;
6251};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006252
6253} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006254
6255bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6256 const analyze_printf::PrintfSpecifier &FS,
6257 const char *startSpecifier,
6258 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006259 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006260 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006261
Ted Kremenekce815422010-07-19 21:25:57 +00006262 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6263 getLocationOfByte(CS.getStart()),
6264 startSpecifier, specifierLen,
6265 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006266}
6267
Ted Kremenek02087932010-07-16 02:11:22 +00006268bool CheckPrintfHandler::HandleAmount(
6269 const analyze_format_string::OptionalAmount &Amt,
6270 unsigned k, const char *startSpecifier,
6271 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006272 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006273 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006274 unsigned argIndex = Amt.getArgIndex();
6275 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006276 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6277 << k,
6278 getLocationOfByte(Amt.getStart()),
6279 /*IsStringLocation*/true,
6280 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006281 // Don't do any more checking. We will just emit
6282 // spurious errors.
6283 return false;
6284 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006285
Ted Kremenek5739de72010-01-29 01:06:55 +00006286 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006287 // Although not in conformance with C99, we also allow the argument to be
6288 // an 'unsigned int' as that is a reasonably safe case. GCC also
6289 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006290 CoveredArgs.set(argIndex);
6291 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006292 if (!Arg)
6293 return false;
6294
Ted Kremenek5739de72010-01-29 01:06:55 +00006295 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006296
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006297 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6298 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006299
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006300 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006301 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006302 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006303 << T << Arg->getSourceRange(),
6304 getLocationOfByte(Amt.getStart()),
6305 /*IsStringLocation*/true,
6306 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006307 // Don't do any more checking. We will just emit
6308 // spurious errors.
6309 return false;
6310 }
6311 }
6312 }
6313 return true;
6314}
Ted Kremenek5739de72010-01-29 01:06:55 +00006315
Tom Careb49ec692010-06-17 19:00:27 +00006316void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006317 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006318 const analyze_printf::OptionalAmount &Amt,
6319 unsigned type,
6320 const char *startSpecifier,
6321 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006322 const analyze_printf::PrintfConversionSpecifier &CS =
6323 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006324
Richard Trieu03cf7b72011-10-28 00:41:25 +00006325 FixItHint fixit =
6326 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6327 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6328 Amt.getConstantLength()))
6329 : FixItHint();
6330
6331 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6332 << type << CS.toString(),
6333 getLocationOfByte(Amt.getStart()),
6334 /*IsStringLocation*/true,
6335 getSpecifierRange(startSpecifier, specifierLen),
6336 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006337}
6338
Ted Kremenek02087932010-07-16 02:11:22 +00006339void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006340 const analyze_printf::OptionalFlag &flag,
6341 const char *startSpecifier,
6342 unsigned specifierLen) {
6343 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006344 const analyze_printf::PrintfConversionSpecifier &CS =
6345 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006346 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6347 << flag.toString() << CS.toString(),
6348 getLocationOfByte(flag.getPosition()),
6349 /*IsStringLocation*/true,
6350 getSpecifierRange(startSpecifier, specifierLen),
6351 FixItHint::CreateRemoval(
6352 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006353}
6354
6355void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006356 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006357 const analyze_printf::OptionalFlag &ignoredFlag,
6358 const analyze_printf::OptionalFlag &flag,
6359 const char *startSpecifier,
6360 unsigned specifierLen) {
6361 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006362 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6363 << ignoredFlag.toString() << flag.toString(),
6364 getLocationOfByte(ignoredFlag.getPosition()),
6365 /*IsStringLocation*/true,
6366 getSpecifierRange(startSpecifier, specifierLen),
6367 FixItHint::CreateRemoval(
6368 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006369}
6370
Ted Kremenek2b417712015-07-02 05:39:16 +00006371void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6372 unsigned flagLen) {
6373 // Warn about an empty flag.
6374 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6375 getLocationOfByte(startFlag),
6376 /*IsStringLocation*/true,
6377 getSpecifierRange(startFlag, flagLen));
6378}
6379
6380void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6381 unsigned flagLen) {
6382 // Warn about an invalid flag.
6383 auto Range = getSpecifierRange(startFlag, flagLen);
6384 StringRef flag(startFlag, flagLen);
6385 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6386 getLocationOfByte(startFlag),
6387 /*IsStringLocation*/true,
6388 Range, FixItHint::CreateRemoval(Range));
6389}
6390
6391void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6392 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6393 // Warn about using '[...]' without a '@' conversion.
6394 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6395 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6396 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6397 getLocationOfByte(conversionPosition),
6398 /*IsStringLocation*/true,
6399 Range, FixItHint::CreateRemoval(Range));
6400}
6401
Richard Smith55ce3522012-06-25 20:30:08 +00006402// Determines if the specified is a C++ class or struct containing
6403// a member with the specified name and kind (e.g. a CXXMethodDecl named
6404// "c_str()").
6405template<typename MemberKind>
6406static llvm::SmallPtrSet<MemberKind*, 1>
6407CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6408 const RecordType *RT = Ty->getAs<RecordType>();
6409 llvm::SmallPtrSet<MemberKind*, 1> Results;
6410
6411 if (!RT)
6412 return Results;
6413 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006414 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006415 return Results;
6416
Alp Tokerb6cc5922014-05-03 03:45:55 +00006417 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006418 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006419 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006420
6421 // We just need to include all members of the right kind turned up by the
6422 // filter, at this point.
6423 if (S.LookupQualifiedName(R, RT->getDecl()))
6424 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6425 NamedDecl *decl = (*I)->getUnderlyingDecl();
6426 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6427 Results.insert(FK);
6428 }
6429 return Results;
6430}
6431
Richard Smith2868a732014-02-28 01:36:39 +00006432/// Check if we could call '.c_str()' on an object.
6433///
6434/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6435/// allow the call, or if it would be ambiguous).
6436bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006437 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6438
Richard Smith2868a732014-02-28 01:36:39 +00006439 MethodSet Results =
6440 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6441 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6442 MI != ME; ++MI)
6443 if ((*MI)->getMinRequiredArguments() == 0)
6444 return true;
6445 return false;
6446}
6447
Richard Smith55ce3522012-06-25 20:30:08 +00006448// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006449// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006450// Returns true when a c_str() conversion method is found.
6451bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006452 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006453 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006454
6455 MethodSet Results =
6456 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6457
6458 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6459 MI != ME; ++MI) {
6460 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006461 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006462 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006463 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006464 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006465 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6466 << "c_str()"
6467 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6468 return true;
6469 }
6470 }
6471
6472 return false;
6473}
6474
Ted Kremenekab278de2010-01-28 23:39:18 +00006475bool
Ted Kremenek02087932010-07-16 02:11:22 +00006476CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006477 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006478 const char *startSpecifier,
6479 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006480 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006481 using namespace analyze_printf;
6482
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006483 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006484
Ted Kremenek6cd69422010-07-19 22:01:06 +00006485 if (FS.consumesDataArgument()) {
6486 if (atFirstArg) {
6487 atFirstArg = false;
6488 usesPositionalArgs = FS.usesPositionalArg();
6489 }
6490 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006491 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6492 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006493 return false;
6494 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006495 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006496
Ted Kremenekd1668192010-02-27 01:41:03 +00006497 // First check if the field width, precision, and conversion specifier
6498 // have matching data arguments.
6499 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6500 startSpecifier, specifierLen)) {
6501 return false;
6502 }
6503
6504 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6505 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006506 return false;
6507 }
6508
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006509 if (!CS.consumesDataArgument()) {
6510 // FIXME: Technically specifying a precision or field width here
6511 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006512 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006513 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006514
Ted Kremenek4a49d982010-02-26 19:18:41 +00006515 // Consume the argument.
6516 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006517 if (argIndex < NumDataArgs) {
6518 // The check to see if the argIndex is valid will come later.
6519 // We set the bit here because we may exit early from this
6520 // function if we encounter some other error.
6521 CoveredArgs.set(argIndex);
6522 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006523
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006524 // FreeBSD kernel extensions.
6525 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6526 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6527 // We need at least two arguments.
6528 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6529 return false;
6530
6531 // Claim the second argument.
6532 CoveredArgs.set(argIndex + 1);
6533
6534 // Type check the first argument (int for %b, pointer for %D)
6535 const Expr *Ex = getDataArg(argIndex);
6536 const analyze_printf::ArgType &AT =
6537 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6538 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6539 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6540 EmitFormatDiagnostic(
6541 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6542 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6543 << false << Ex->getSourceRange(),
6544 Ex->getLocStart(), /*IsStringLocation*/false,
6545 getSpecifierRange(startSpecifier, specifierLen));
6546
6547 // Type check the second argument (char * for both %b and %D)
6548 Ex = getDataArg(argIndex + 1);
6549 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6550 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6551 EmitFormatDiagnostic(
6552 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6553 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6554 << false << Ex->getSourceRange(),
6555 Ex->getLocStart(), /*IsStringLocation*/false,
6556 getSpecifierRange(startSpecifier, specifierLen));
6557
6558 return true;
6559 }
6560
Ted Kremenek4a49d982010-02-26 19:18:41 +00006561 // Check for using an Objective-C specific conversion specifier
6562 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006563 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006564 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6565 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006566 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006567
Mehdi Amini06d367c2016-10-24 20:39:34 +00006568 // %P can only be used with os_log.
6569 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6570 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6571 specifierLen);
6572 }
6573
6574 // %n is not allowed with os_log.
6575 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6576 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6577 getLocationOfByte(CS.getStart()),
6578 /*IsStringLocation*/ false,
6579 getSpecifierRange(startSpecifier, specifierLen));
6580
6581 return true;
6582 }
6583
6584 // Only scalars are allowed for os_trace.
6585 if (FSType == Sema::FST_OSTrace &&
6586 (CS.getKind() == ConversionSpecifier::PArg ||
6587 CS.getKind() == ConversionSpecifier::sArg ||
6588 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6589 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6590 specifierLen);
6591 }
6592
6593 // Check for use of public/private annotation outside of os_log().
6594 if (FSType != Sema::FST_OSLog) {
6595 if (FS.isPublic().isSet()) {
6596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6597 << "public",
6598 getLocationOfByte(FS.isPublic().getPosition()),
6599 /*IsStringLocation*/ false,
6600 getSpecifierRange(startSpecifier, specifierLen));
6601 }
6602 if (FS.isPrivate().isSet()) {
6603 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6604 << "private",
6605 getLocationOfByte(FS.isPrivate().getPosition()),
6606 /*IsStringLocation*/ false,
6607 getSpecifierRange(startSpecifier, specifierLen));
6608 }
6609 }
6610
Tom Careb49ec692010-06-17 19:00:27 +00006611 // Check for invalid use of field width
6612 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006613 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006614 startSpecifier, specifierLen);
6615 }
6616
6617 // Check for invalid use of precision
6618 if (!FS.hasValidPrecision()) {
6619 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6620 startSpecifier, specifierLen);
6621 }
6622
Mehdi Amini06d367c2016-10-24 20:39:34 +00006623 // Precision is mandatory for %P specifier.
6624 if (CS.getKind() == ConversionSpecifier::PArg &&
6625 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6626 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6627 getLocationOfByte(startSpecifier),
6628 /*IsStringLocation*/ false,
6629 getSpecifierRange(startSpecifier, specifierLen));
6630 }
6631
Tom Careb49ec692010-06-17 19:00:27 +00006632 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006633 if (!FS.hasValidThousandsGroupingPrefix())
6634 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006635 if (!FS.hasValidLeadingZeros())
6636 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6637 if (!FS.hasValidPlusPrefix())
6638 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006639 if (!FS.hasValidSpacePrefix())
6640 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006641 if (!FS.hasValidAlternativeForm())
6642 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6643 if (!FS.hasValidLeftJustified())
6644 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6645
6646 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006647 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6648 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6649 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006650 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6651 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6652 startSpecifier, specifierLen);
6653
6654 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006655 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006656 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6657 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006658 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006659 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006660 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006661 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6662 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006663
Jordan Rose92303592012-09-08 04:00:03 +00006664 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6665 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6666
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006667 // The remaining checks depend on the data arguments.
6668 if (HasVAListArg)
6669 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006670
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006671 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006672 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006673
Jordan Rose58bbe422012-07-19 18:10:08 +00006674 const Expr *Arg = getDataArg(argIndex);
6675 if (!Arg)
6676 return true;
6677
6678 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006679}
6680
Jordan Roseaee34382012-09-05 22:56:26 +00006681static bool requiresParensToAddCast(const Expr *E) {
6682 // FIXME: We should have a general way to reason about operator
6683 // precedence and whether parens are actually needed here.
6684 // Take care of a few common cases where they aren't.
6685 const Expr *Inside = E->IgnoreImpCasts();
6686 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6687 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6688
6689 switch (Inside->getStmtClass()) {
6690 case Stmt::ArraySubscriptExprClass:
6691 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006692 case Stmt::CharacterLiteralClass:
6693 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006694 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006695 case Stmt::FloatingLiteralClass:
6696 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006697 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006698 case Stmt::ObjCArrayLiteralClass:
6699 case Stmt::ObjCBoolLiteralExprClass:
6700 case Stmt::ObjCBoxedExprClass:
6701 case Stmt::ObjCDictionaryLiteralClass:
6702 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006703 case Stmt::ObjCIvarRefExprClass:
6704 case Stmt::ObjCMessageExprClass:
6705 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006706 case Stmt::ObjCStringLiteralClass:
6707 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006708 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006709 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006710 case Stmt::UnaryOperatorClass:
6711 return false;
6712 default:
6713 return true;
6714 }
6715}
6716
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006717static std::pair<QualType, StringRef>
6718shouldNotPrintDirectly(const ASTContext &Context,
6719 QualType IntendedTy,
6720 const Expr *E) {
6721 // Use a 'while' to peel off layers of typedefs.
6722 QualType TyTy = IntendedTy;
6723 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6724 StringRef Name = UserTy->getDecl()->getName();
6725 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006726 .Case("CFIndex", Context.getNSIntegerType())
6727 .Case("NSInteger", Context.getNSIntegerType())
6728 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006729 .Case("SInt32", Context.IntTy)
6730 .Case("UInt32", Context.UnsignedIntTy)
6731 .Default(QualType());
6732
6733 if (!CastTy.isNull())
6734 return std::make_pair(CastTy, Name);
6735
6736 TyTy = UserTy->desugar();
6737 }
6738
6739 // Strip parens if necessary.
6740 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6741 return shouldNotPrintDirectly(Context,
6742 PE->getSubExpr()->getType(),
6743 PE->getSubExpr());
6744
6745 // If this is a conditional expression, then its result type is constructed
6746 // via usual arithmetic conversions and thus there might be no necessary
6747 // typedef sugar there. Recurse to operands to check for NSInteger &
6748 // Co. usage condition.
6749 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6750 QualType TrueTy, FalseTy;
6751 StringRef TrueName, FalseName;
6752
6753 std::tie(TrueTy, TrueName) =
6754 shouldNotPrintDirectly(Context,
6755 CO->getTrueExpr()->getType(),
6756 CO->getTrueExpr());
6757 std::tie(FalseTy, FalseName) =
6758 shouldNotPrintDirectly(Context,
6759 CO->getFalseExpr()->getType(),
6760 CO->getFalseExpr());
6761
6762 if (TrueTy == FalseTy)
6763 return std::make_pair(TrueTy, TrueName);
6764 else if (TrueTy.isNull())
6765 return std::make_pair(FalseTy, FalseName);
6766 else if (FalseTy.isNull())
6767 return std::make_pair(TrueTy, TrueName);
6768 }
6769
6770 return std::make_pair(QualType(), StringRef());
6771}
6772
Richard Smith55ce3522012-06-25 20:30:08 +00006773bool
6774CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6775 const char *StartSpecifier,
6776 unsigned SpecifierLen,
6777 const Expr *E) {
6778 using namespace analyze_format_string;
6779 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006780
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006781 // Now type check the data expression that matches the
6782 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006783 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006784 if (!AT.isValid())
6785 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006786
Jordan Rose598ec092012-12-05 18:44:40 +00006787 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006788 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6789 ExprTy = TET->getUnderlyingExpr()->getType();
6790 }
6791
Seth Cantrellb4802962015-03-04 03:12:10 +00006792 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6793
6794 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006795 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006796 }
Jordan Rose98709982012-06-04 22:48:57 +00006797
Jordan Rose22b74712012-09-05 22:56:19 +00006798 // Look through argument promotions for our error message's reported type.
6799 // This includes the integral and floating promotions, but excludes array
6800 // and function pointer decay; seeing that an argument intended to be a
6801 // string has type 'char [6]' is probably more confusing than 'char *'.
6802 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6803 if (ICE->getCastKind() == CK_IntegralCast ||
6804 ICE->getCastKind() == CK_FloatingCast) {
6805 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006806 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006807
6808 // Check if we didn't match because of an implicit cast from a 'char'
6809 // or 'short' to an 'int'. This is done because printf is a varargs
6810 // function.
6811 if (ICE->getType() == S.Context.IntTy ||
6812 ICE->getType() == S.Context.UnsignedIntTy) {
6813 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006814 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006815 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006816 }
Jordan Rose98709982012-06-04 22:48:57 +00006817 }
Jordan Rose598ec092012-12-05 18:44:40 +00006818 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6819 // Special case for 'a', which has type 'int' in C.
6820 // Note, however, that we do /not/ want to treat multibyte constants like
6821 // 'MooV' as characters! This form is deprecated but still exists.
6822 if (ExprTy == S.Context.IntTy)
6823 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6824 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006825 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006826
Jordan Rosebc53ed12014-05-31 04:12:14 +00006827 // Look through enums to their underlying type.
6828 bool IsEnum = false;
6829 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6830 ExprTy = EnumTy->getDecl()->getIntegerType();
6831 IsEnum = true;
6832 }
6833
Jordan Rose0e5badd2012-12-05 18:44:49 +00006834 // %C in an Objective-C context prints a unichar, not a wchar_t.
6835 // If the argument is an integer of some kind, believe the %C and suggest
6836 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006837 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006838 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006839 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6840 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6841 !ExprTy->isCharType()) {
6842 // 'unichar' is defined as a typedef of unsigned short, but we should
6843 // prefer using the typedef if it is visible.
6844 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006845
6846 // While we are here, check if the value is an IntegerLiteral that happens
6847 // to be within the valid range.
6848 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6849 const llvm::APInt &V = IL->getValue();
6850 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6851 return true;
6852 }
6853
Jordan Rose0e5badd2012-12-05 18:44:49 +00006854 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6855 Sema::LookupOrdinaryName);
6856 if (S.LookupName(Result, S.getCurScope())) {
6857 NamedDecl *ND = Result.getFoundDecl();
6858 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6859 if (TD->getUnderlyingType() == IntendedTy)
6860 IntendedTy = S.Context.getTypedefType(TD);
6861 }
6862 }
6863 }
6864
6865 // Special-case some of Darwin's platform-independence types by suggesting
6866 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006867 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006868 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006869 QualType CastTy;
6870 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6871 if (!CastTy.isNull()) {
6872 IntendedTy = CastTy;
6873 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006874 }
6875 }
6876
Jordan Rose22b74712012-09-05 22:56:19 +00006877 // We may be able to offer a FixItHint if it is a supported type.
6878 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006879 bool success =
6880 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006881
Jordan Rose22b74712012-09-05 22:56:19 +00006882 if (success) {
6883 // Get the fix string from the fixed format specifier
6884 SmallString<16> buf;
6885 llvm::raw_svector_ostream os(buf);
6886 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006887
Jordan Roseaee34382012-09-05 22:56:26 +00006888 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6889
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006890 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006891 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6892 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6893 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6894 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006895 // In this case, the specifier is wrong and should be changed to match
6896 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006897 EmitFormatDiagnostic(S.PDiag(diag)
6898 << AT.getRepresentativeTypeName(S.Context)
6899 << IntendedTy << IsEnum << E->getSourceRange(),
6900 E->getLocStart(),
6901 /*IsStringLocation*/ false, SpecRange,
6902 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006903 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006904 // The canonical type for formatting this value is different from the
6905 // actual type of the expression. (This occurs, for example, with Darwin's
6906 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6907 // should be printed as 'long' for 64-bit compatibility.)
6908 // Rather than emitting a normal format/argument mismatch, we want to
6909 // add a cast to the recommended type (and correct the format string
6910 // if necessary).
6911 SmallString<16> CastBuf;
6912 llvm::raw_svector_ostream CastFix(CastBuf);
6913 CastFix << "(";
6914 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6915 CastFix << ")";
6916
6917 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006918 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006919 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6920
6921 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6922 // If there's already a cast present, just replace it.
6923 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6924 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6925
6926 } else if (!requiresParensToAddCast(E)) {
6927 // If the expression has high enough precedence,
6928 // just write the C-style cast.
6929 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6930 CastFix.str()));
6931 } else {
6932 // Otherwise, add parens around the expression as well as the cast.
6933 CastFix << "(";
6934 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6935 CastFix.str()));
6936
Alp Tokerb6cc5922014-05-03 03:45:55 +00006937 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006938 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6939 }
6940
Jordan Rose0e5badd2012-12-05 18:44:49 +00006941 if (ShouldNotPrintDirectly) {
6942 // The expression has a type that should not be printed directly.
6943 // We extract the name from the typedef because we don't want to show
6944 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006945 StringRef Name;
6946 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6947 Name = TypedefTy->getDecl()->getName();
6948 else
6949 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006950 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006951 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006952 << E->getSourceRange(),
6953 E->getLocStart(), /*IsStringLocation=*/false,
6954 SpecRange, Hints);
6955 } else {
6956 // In this case, the expression could be printed using a different
6957 // specifier, but we've decided that the specifier is probably correct
6958 // and we should cast instead. Just use the normal warning message.
6959 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006960 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6961 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006962 << E->getSourceRange(),
6963 E->getLocStart(), /*IsStringLocation*/false,
6964 SpecRange, Hints);
6965 }
Jordan Roseaee34382012-09-05 22:56:26 +00006966 }
Jordan Rose22b74712012-09-05 22:56:19 +00006967 } else {
6968 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6969 SpecifierLen);
6970 // Since the warning for passing non-POD types to variadic functions
6971 // was deferred until now, we emit a warning for non-POD
6972 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006973 switch (S.isValidVarArgType(ExprTy)) {
6974 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006975 case Sema::VAK_ValidInCXX11: {
6976 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6977 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6978 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6979 }
Richard Smithd7293d72013-08-05 18:49:43 +00006980
Seth Cantrellb4802962015-03-04 03:12:10 +00006981 EmitFormatDiagnostic(
6982 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6983 << IsEnum << CSR << E->getSourceRange(),
6984 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6985 break;
6986 }
Richard Smithd7293d72013-08-05 18:49:43 +00006987 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006988 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006989 EmitFormatDiagnostic(
6990 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006991 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006992 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006993 << CallType
6994 << AT.getRepresentativeTypeName(S.Context)
6995 << CSR
6996 << E->getSourceRange(),
6997 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006998 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006999 break;
7000
7001 case Sema::VAK_Invalid:
7002 if (ExprTy->isObjCObjectType())
7003 EmitFormatDiagnostic(
7004 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7005 << S.getLangOpts().CPlusPlus11
7006 << ExprTy
7007 << CallType
7008 << AT.getRepresentativeTypeName(S.Context)
7009 << CSR
7010 << E->getSourceRange(),
7011 E->getLocStart(), /*IsStringLocation*/false, CSR);
7012 else
7013 // FIXME: If this is an initializer list, suggest removing the braces
7014 // or inserting a cast to the target type.
7015 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
7016 << isa<InitListExpr>(E) << ExprTy << CallType
7017 << AT.getRepresentativeTypeName(S.Context)
7018 << E->getSourceRange();
7019 break;
7020 }
7021
7022 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7023 "format string specifier index out of range");
7024 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007025 }
7026
Ted Kremenekab278de2010-01-28 23:39:18 +00007027 return true;
7028}
7029
Ted Kremenek02087932010-07-16 02:11:22 +00007030//===--- CHECK: Scanf format string checking ------------------------------===//
7031
7032namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007033
Ted Kremenek02087932010-07-16 02:11:22 +00007034class CheckScanfHandler : public CheckFormatHandler {
7035public:
Stephen Hines648c3692016-09-16 01:07:04 +00007036 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007037 const Expr *origFormatExpr, Sema::FormatStringType type,
7038 unsigned firstDataArg, unsigned numDataArgs,
7039 const char *beg, bool hasVAListArg,
7040 ArrayRef<const Expr *> Args, unsigned formatIdx,
7041 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007042 llvm::SmallBitVector &CheckedVarArgs,
7043 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007044 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7045 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7046 inFunctionCall, CallType, CheckedVarArgs,
7047 UncoveredArg) {}
7048
Ted Kremenek02087932010-07-16 02:11:22 +00007049 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7050 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007051 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00007052
7053 bool HandleInvalidScanfConversionSpecifier(
7054 const analyze_scanf::ScanfSpecifier &FS,
7055 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007056 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007057
Craig Toppere14c0f82014-03-12 04:55:44 +00007058 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00007059};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007060
7061} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007062
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007063void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7064 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007065 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7066 getLocationOfByte(end), /*IsStringLocation*/true,
7067 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007068}
7069
Ted Kremenekce815422010-07-19 21:25:57 +00007070bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7071 const analyze_scanf::ScanfSpecifier &FS,
7072 const char *startSpecifier,
7073 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007074 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007075 FS.getConversionSpecifier();
7076
7077 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7078 getLocationOfByte(CS.getStart()),
7079 startSpecifier, specifierLen,
7080 CS.getStart(), CS.getLength());
7081}
7082
Ted Kremenek02087932010-07-16 02:11:22 +00007083bool CheckScanfHandler::HandleScanfSpecifier(
7084 const analyze_scanf::ScanfSpecifier &FS,
7085 const char *startSpecifier,
7086 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00007087 using namespace analyze_scanf;
7088 using namespace analyze_format_string;
7089
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007090 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00007091
Ted Kremenek6cd69422010-07-19 22:01:06 +00007092 // Handle case where '%' and '*' don't consume an argument. These shouldn't
7093 // be used to decide if we are using positional arguments consistently.
7094 if (FS.consumesDataArgument()) {
7095 if (atFirstArg) {
7096 atFirstArg = false;
7097 usesPositionalArgs = FS.usesPositionalArg();
7098 }
7099 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007100 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7101 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007102 return false;
7103 }
Ted Kremenek02087932010-07-16 02:11:22 +00007104 }
7105
7106 // Check if the field with is non-zero.
7107 const OptionalAmount &Amt = FS.getFieldWidth();
7108 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7109 if (Amt.getConstantAmount() == 0) {
7110 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7111 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00007112 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7113 getLocationOfByte(Amt.getStart()),
7114 /*IsStringLocation*/true, R,
7115 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00007116 }
7117 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007118
Ted Kremenek02087932010-07-16 02:11:22 +00007119 if (!FS.consumesDataArgument()) {
7120 // FIXME: Technically specifying a precision or field width here
7121 // makes no sense. Worth issuing a warning at some point.
7122 return true;
7123 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007124
Ted Kremenek02087932010-07-16 02:11:22 +00007125 // Consume the argument.
7126 unsigned argIndex = FS.getArgIndex();
7127 if (argIndex < NumDataArgs) {
7128 // The check to see if the argIndex is valid will come later.
7129 // We set the bit here because we may exit early from this
7130 // function if we encounter some other error.
7131 CoveredArgs.set(argIndex);
7132 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007133
Ted Kremenek4407ea42010-07-20 20:04:47 +00007134 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007135 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007136 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7137 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007138 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007139 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007140 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007141 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7142 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007143
Jordan Rose92303592012-09-08 04:00:03 +00007144 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7145 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7146
Ted Kremenek02087932010-07-16 02:11:22 +00007147 // The remaining checks depend on the data arguments.
7148 if (HasVAListArg)
7149 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007150
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007151 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00007152 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00007153
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007154 // Check that the argument type matches the format specifier.
7155 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007156 if (!Ex)
7157 return true;
7158
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00007159 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00007160
7161 if (!AT.isValid()) {
7162 return true;
7163 }
7164
Seth Cantrellb4802962015-03-04 03:12:10 +00007165 analyze_format_string::ArgType::MatchKind match =
7166 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00007167 if (match == analyze_format_string::ArgType::Match) {
7168 return true;
7169 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007170
Seth Cantrell79340072015-03-04 05:58:08 +00007171 ScanfSpecifier fixedFS = FS;
7172 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
7173 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007174
Seth Cantrell79340072015-03-04 05:58:08 +00007175 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
7176 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
7177 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
7178 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007179
Seth Cantrell79340072015-03-04 05:58:08 +00007180 if (success) {
7181 // Get the fix string from the fixed format specifier.
7182 SmallString<128> buf;
7183 llvm::raw_svector_ostream os(buf);
7184 fixedFS.toString(os);
7185
7186 EmitFormatDiagnostic(
7187 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7188 << Ex->getType() << false << Ex->getSourceRange(),
7189 Ex->getLocStart(),
7190 /*IsStringLocation*/ false,
7191 getSpecifierRange(startSpecifier, specifierLen),
7192 FixItHint::CreateReplacement(
7193 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7194 } else {
7195 EmitFormatDiagnostic(S.PDiag(diag)
7196 << AT.getRepresentativeTypeName(S.Context)
7197 << Ex->getType() << false << Ex->getSourceRange(),
7198 Ex->getLocStart(),
7199 /*IsStringLocation*/ false,
7200 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007201 }
7202
Ted Kremenek02087932010-07-16 02:11:22 +00007203 return true;
7204}
7205
Stephen Hines648c3692016-09-16 01:07:04 +00007206static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007207 const Expr *OrigFormatExpr,
7208 ArrayRef<const Expr *> Args,
7209 bool HasVAListArg, unsigned format_idx,
7210 unsigned firstDataArg,
7211 Sema::FormatStringType Type,
7212 bool inFunctionCall,
7213 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007214 llvm::SmallBitVector &CheckedVarArgs,
7215 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007216 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007217 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007218 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007219 S, inFunctionCall, Args[format_idx],
7220 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007221 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007222 return;
7223 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007224
Ted Kremenekab278de2010-01-28 23:39:18 +00007225 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007226 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007227 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007228 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007229 const ConstantArrayType *T =
7230 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007231 assert(T && "String literal not of constant array type!");
7232 size_t TypeSize = T->getSize().getZExtValue();
7233 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007234 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007235
7236 // Emit a warning if the string literal is truncated and does not contain an
7237 // embedded null character.
7238 if (TypeSize <= StrRef.size() &&
7239 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7240 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007241 S, inFunctionCall, Args[format_idx],
7242 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007243 FExpr->getLocStart(),
7244 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7245 return;
7246 }
7247
Ted Kremenekab278de2010-01-28 23:39:18 +00007248 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007249 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007250 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007251 S, inFunctionCall, Args[format_idx],
7252 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007253 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007254 return;
7255 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007256
7257 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007258 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7259 Type == Sema::FST_OSTrace) {
7260 CheckPrintfHandler H(
7261 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7262 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7263 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7264 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007265
Hans Wennborg23926bd2011-12-15 10:25:47 +00007266 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007267 S.getLangOpts(),
7268 S.Context.getTargetInfo(),
7269 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007270 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007271 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007272 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7273 numDataArgs, Str, HasVAListArg, Args, format_idx,
7274 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007275
Hans Wennborg23926bd2011-12-15 10:25:47 +00007276 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007277 S.getLangOpts(),
7278 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007279 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007280 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007281}
7282
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007283bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7284 // Str - The format string. NOTE: this is NOT null-terminated!
7285 StringRef StrRef = FExpr->getString();
7286 const char *Str = StrRef.data();
7287 // Account for cases where the string literal is truncated in a declaration.
7288 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7289 assert(T && "String literal not of constant array type!");
7290 size_t TypeSize = T->getSize().getZExtValue();
7291 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7292 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7293 getLangOpts(),
7294 Context.getTargetInfo());
7295}
7296
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007297//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7298
7299// Returns the related absolute value function that is larger, of 0 if one
7300// does not exist.
7301static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7302 switch (AbsFunction) {
7303 default:
7304 return 0;
7305
7306 case Builtin::BI__builtin_abs:
7307 return Builtin::BI__builtin_labs;
7308 case Builtin::BI__builtin_labs:
7309 return Builtin::BI__builtin_llabs;
7310 case Builtin::BI__builtin_llabs:
7311 return 0;
7312
7313 case Builtin::BI__builtin_fabsf:
7314 return Builtin::BI__builtin_fabs;
7315 case Builtin::BI__builtin_fabs:
7316 return Builtin::BI__builtin_fabsl;
7317 case Builtin::BI__builtin_fabsl:
7318 return 0;
7319
7320 case Builtin::BI__builtin_cabsf:
7321 return Builtin::BI__builtin_cabs;
7322 case Builtin::BI__builtin_cabs:
7323 return Builtin::BI__builtin_cabsl;
7324 case Builtin::BI__builtin_cabsl:
7325 return 0;
7326
7327 case Builtin::BIabs:
7328 return Builtin::BIlabs;
7329 case Builtin::BIlabs:
7330 return Builtin::BIllabs;
7331 case Builtin::BIllabs:
7332 return 0;
7333
7334 case Builtin::BIfabsf:
7335 return Builtin::BIfabs;
7336 case Builtin::BIfabs:
7337 return Builtin::BIfabsl;
7338 case Builtin::BIfabsl:
7339 return 0;
7340
7341 case Builtin::BIcabsf:
7342 return Builtin::BIcabs;
7343 case Builtin::BIcabs:
7344 return Builtin::BIcabsl;
7345 case Builtin::BIcabsl:
7346 return 0;
7347 }
7348}
7349
7350// Returns the argument type of the absolute value function.
7351static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7352 unsigned AbsType) {
7353 if (AbsType == 0)
7354 return QualType();
7355
7356 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7357 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7358 if (Error != ASTContext::GE_None)
7359 return QualType();
7360
7361 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7362 if (!FT)
7363 return QualType();
7364
7365 if (FT->getNumParams() != 1)
7366 return QualType();
7367
7368 return FT->getParamType(0);
7369}
7370
7371// Returns the best absolute value function, or zero, based on type and
7372// current absolute value function.
7373static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7374 unsigned AbsFunctionKind) {
7375 unsigned BestKind = 0;
7376 uint64_t ArgSize = Context.getTypeSize(ArgType);
7377 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7378 Kind = getLargerAbsoluteValueFunction(Kind)) {
7379 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7380 if (Context.getTypeSize(ParamType) >= ArgSize) {
7381 if (BestKind == 0)
7382 BestKind = Kind;
7383 else if (Context.hasSameType(ParamType, ArgType)) {
7384 BestKind = Kind;
7385 break;
7386 }
7387 }
7388 }
7389 return BestKind;
7390}
7391
7392enum AbsoluteValueKind {
7393 AVK_Integer,
7394 AVK_Floating,
7395 AVK_Complex
7396};
7397
7398static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7399 if (T->isIntegralOrEnumerationType())
7400 return AVK_Integer;
7401 if (T->isRealFloatingType())
7402 return AVK_Floating;
7403 if (T->isAnyComplexType())
7404 return AVK_Complex;
7405
7406 llvm_unreachable("Type not integer, floating, or complex");
7407}
7408
7409// Changes the absolute value function to a different type. Preserves whether
7410// the function is a builtin.
7411static unsigned changeAbsFunction(unsigned AbsKind,
7412 AbsoluteValueKind ValueKind) {
7413 switch (ValueKind) {
7414 case AVK_Integer:
7415 switch (AbsKind) {
7416 default:
7417 return 0;
7418 case Builtin::BI__builtin_fabsf:
7419 case Builtin::BI__builtin_fabs:
7420 case Builtin::BI__builtin_fabsl:
7421 case Builtin::BI__builtin_cabsf:
7422 case Builtin::BI__builtin_cabs:
7423 case Builtin::BI__builtin_cabsl:
7424 return Builtin::BI__builtin_abs;
7425 case Builtin::BIfabsf:
7426 case Builtin::BIfabs:
7427 case Builtin::BIfabsl:
7428 case Builtin::BIcabsf:
7429 case Builtin::BIcabs:
7430 case Builtin::BIcabsl:
7431 return Builtin::BIabs;
7432 }
7433 case AVK_Floating:
7434 switch (AbsKind) {
7435 default:
7436 return 0;
7437 case Builtin::BI__builtin_abs:
7438 case Builtin::BI__builtin_labs:
7439 case Builtin::BI__builtin_llabs:
7440 case Builtin::BI__builtin_cabsf:
7441 case Builtin::BI__builtin_cabs:
7442 case Builtin::BI__builtin_cabsl:
7443 return Builtin::BI__builtin_fabsf;
7444 case Builtin::BIabs:
7445 case Builtin::BIlabs:
7446 case Builtin::BIllabs:
7447 case Builtin::BIcabsf:
7448 case Builtin::BIcabs:
7449 case Builtin::BIcabsl:
7450 return Builtin::BIfabsf;
7451 }
7452 case AVK_Complex:
7453 switch (AbsKind) {
7454 default:
7455 return 0;
7456 case Builtin::BI__builtin_abs:
7457 case Builtin::BI__builtin_labs:
7458 case Builtin::BI__builtin_llabs:
7459 case Builtin::BI__builtin_fabsf:
7460 case Builtin::BI__builtin_fabs:
7461 case Builtin::BI__builtin_fabsl:
7462 return Builtin::BI__builtin_cabsf;
7463 case Builtin::BIabs:
7464 case Builtin::BIlabs:
7465 case Builtin::BIllabs:
7466 case Builtin::BIfabsf:
7467 case Builtin::BIfabs:
7468 case Builtin::BIfabsl:
7469 return Builtin::BIcabsf;
7470 }
7471 }
7472 llvm_unreachable("Unable to convert function");
7473}
7474
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007475static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007476 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7477 if (!FnInfo)
7478 return 0;
7479
7480 switch (FDecl->getBuiltinID()) {
7481 default:
7482 return 0;
7483 case Builtin::BI__builtin_abs:
7484 case Builtin::BI__builtin_fabs:
7485 case Builtin::BI__builtin_fabsf:
7486 case Builtin::BI__builtin_fabsl:
7487 case Builtin::BI__builtin_labs:
7488 case Builtin::BI__builtin_llabs:
7489 case Builtin::BI__builtin_cabs:
7490 case Builtin::BI__builtin_cabsf:
7491 case Builtin::BI__builtin_cabsl:
7492 case Builtin::BIabs:
7493 case Builtin::BIlabs:
7494 case Builtin::BIllabs:
7495 case Builtin::BIfabs:
7496 case Builtin::BIfabsf:
7497 case Builtin::BIfabsl:
7498 case Builtin::BIcabs:
7499 case Builtin::BIcabsf:
7500 case Builtin::BIcabsl:
7501 return FDecl->getBuiltinID();
7502 }
7503 llvm_unreachable("Unknown Builtin type");
7504}
7505
7506// If the replacement is valid, emit a note with replacement function.
7507// Additionally, suggest including the proper header if not already included.
7508static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007509 unsigned AbsKind, QualType ArgType) {
7510 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007511 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007512 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007513 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7514 FunctionName = "std::abs";
7515 if (ArgType->isIntegralOrEnumerationType()) {
7516 HeaderName = "cstdlib";
7517 } else if (ArgType->isRealFloatingType()) {
7518 HeaderName = "cmath";
7519 } else {
7520 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007521 }
Richard Trieubeffb832014-04-15 23:47:53 +00007522
7523 // Lookup all std::abs
7524 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007525 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007526 R.suppressDiagnostics();
7527 S.LookupQualifiedName(R, Std);
7528
7529 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007530 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007531 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7532 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7533 } else {
7534 FDecl = dyn_cast<FunctionDecl>(I);
7535 }
7536 if (!FDecl)
7537 continue;
7538
7539 // Found std::abs(), check that they are the right ones.
7540 if (FDecl->getNumParams() != 1)
7541 continue;
7542
7543 // Check that the parameter type can handle the argument.
7544 QualType ParamType = FDecl->getParamDecl(0)->getType();
7545 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7546 S.Context.getTypeSize(ArgType) <=
7547 S.Context.getTypeSize(ParamType)) {
7548 // Found a function, don't need the header hint.
7549 EmitHeaderHint = false;
7550 break;
7551 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007552 }
Richard Trieubeffb832014-04-15 23:47:53 +00007553 }
7554 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007555 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007556 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7557
7558 if (HeaderName) {
7559 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7560 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7561 R.suppressDiagnostics();
7562 S.LookupName(R, S.getCurScope());
7563
7564 if (R.isSingleResult()) {
7565 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7566 if (FD && FD->getBuiltinID() == AbsKind) {
7567 EmitHeaderHint = false;
7568 } else {
7569 return;
7570 }
7571 } else if (!R.empty()) {
7572 return;
7573 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007574 }
7575 }
7576
7577 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007578 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007579
Richard Trieubeffb832014-04-15 23:47:53 +00007580 if (!HeaderName)
7581 return;
7582
7583 if (!EmitHeaderHint)
7584 return;
7585
Alp Toker5d96e0a2014-07-11 20:53:51 +00007586 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7587 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007588}
7589
Richard Trieua7f30b12016-12-06 01:42:28 +00007590template <std::size_t StrLen>
7591static bool IsStdFunction(const FunctionDecl *FDecl,
7592 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007593 if (!FDecl)
7594 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007595 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007596 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007597 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007598 return false;
7599
7600 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007601}
7602
7603// Warn when using the wrong abs() function.
7604void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007605 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007606 if (Call->getNumArgs() != 1)
7607 return;
7608
7609 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007610 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007611 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007612 return;
7613
7614 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7615 QualType ParamType = Call->getArg(0)->getType();
7616
Alp Toker5d96e0a2014-07-11 20:53:51 +00007617 // Unsigned types cannot be negative. Suggest removing the absolute value
7618 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007619 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007620 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007621 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007622 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7623 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007624 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007625 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7626 return;
7627 }
7628
David Majnemer7f77eb92015-11-15 03:04:34 +00007629 // Taking the absolute value of a pointer is very suspicious, they probably
7630 // wanted to index into an array, dereference a pointer, call a function, etc.
7631 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7632 unsigned DiagType = 0;
7633 if (ArgType->isFunctionType())
7634 DiagType = 1;
7635 else if (ArgType->isArrayType())
7636 DiagType = 2;
7637
7638 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7639 return;
7640 }
7641
Richard Trieubeffb832014-04-15 23:47:53 +00007642 // std::abs has overloads which prevent most of the absolute value problems
7643 // from occurring.
7644 if (IsStdAbs)
7645 return;
7646
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007647 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7648 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7649
7650 // The argument and parameter are the same kind. Check if they are the right
7651 // size.
7652 if (ArgValueKind == ParamValueKind) {
7653 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7654 return;
7655
7656 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7657 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7658 << FDecl << ArgType << ParamType;
7659
7660 if (NewAbsKind == 0)
7661 return;
7662
7663 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007664 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007665 return;
7666 }
7667
7668 // ArgValueKind != ParamValueKind
7669 // The wrong type of absolute value function was used. Attempt to find the
7670 // proper one.
7671 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7672 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7673 if (NewAbsKind == 0)
7674 return;
7675
7676 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7677 << FDecl << ParamValueKind << ArgValueKind;
7678
7679 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007680 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007681}
7682
Richard Trieu67c00712016-12-05 23:41:46 +00007683//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007684void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7685 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007686 if (!Call || !FDecl) return;
7687
7688 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007689 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007690 if (Call->getExprLoc().isMacroID()) return;
7691
7692 // Only care about the one template argument, two function parameter std::max
7693 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007694 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007695 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7696 if (!ArgList) return;
7697 if (ArgList->size() != 1) return;
7698
7699 // Check that template type argument is unsigned integer.
7700 const auto& TA = ArgList->get(0);
7701 if (TA.getKind() != TemplateArgument::Type) return;
7702 QualType ArgType = TA.getAsType();
7703 if (!ArgType->isUnsignedIntegerType()) return;
7704
7705 // See if either argument is a literal zero.
7706 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7707 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7708 if (!MTE) return false;
7709 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7710 if (!Num) return false;
7711 if (Num->getValue() != 0) return false;
7712 return true;
7713 };
7714
7715 const Expr *FirstArg = Call->getArg(0);
7716 const Expr *SecondArg = Call->getArg(1);
7717 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7718 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7719
7720 // Only warn when exactly one argument is zero.
7721 if (IsFirstArgZero == IsSecondArgZero) return;
7722
7723 SourceRange FirstRange = FirstArg->getSourceRange();
7724 SourceRange SecondRange = SecondArg->getSourceRange();
7725
7726 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7727
7728 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7729 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7730
7731 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7732 SourceRange RemovalRange;
7733 if (IsFirstArgZero) {
7734 RemovalRange = SourceRange(FirstRange.getBegin(),
7735 SecondRange.getBegin().getLocWithOffset(-1));
7736 } else {
7737 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7738 SecondRange.getEnd());
7739 }
7740
7741 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7742 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7743 << FixItHint::CreateRemoval(RemovalRange);
7744}
7745
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007746//===--- CHECK: Standard memory functions ---------------------------------===//
7747
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007748/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007749/// such as memcmp, strncat, etc and warns if it's a comparison.
7750///
7751/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7752static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7753 IdentifierInfo *FnName,
7754 SourceLocation FnLoc,
7755 SourceLocation RParenLoc) {
7756 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7757 if (!Size)
7758 return false;
7759
Richard Smithc70f1d62017-12-14 15:16:18 +00007760 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7761 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007762 return false;
7763
Nico Weber0e6daef2013-12-26 23:38:39 +00007764 SourceRange SizeRange = Size->getSourceRange();
7765 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7766 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007767 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007768 << FnName << FixItHint::CreateInsertion(
7769 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007770 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007771 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007772 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007773 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7774 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007775
7776 return true;
7777}
7778
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007779/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007780/// (e.g., whether it has a vtable).
7781static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7782 bool &IsContained) {
7783 // Look through array types while ignoring qualifiers.
7784 const Type *Ty = T->getBaseElementTypeUnsafe();
7785 IsContained = false;
7786
7787 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7788 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007789 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007790 return nullptr;
7791
7792 if (RD->isDynamicClass())
7793 return RD;
7794
7795 // Check all the fields. If any bases were dynamic, the class is dynamic.
7796 // It's impossible for a class to transitively contain itself by value, so
7797 // infinite recursion is impossible.
7798 for (auto *FD : RD->fields()) {
7799 bool SubContained;
7800 if (const CXXRecordDecl *ContainedRD =
7801 getContainedDynamicClass(FD->getType(), SubContained)) {
7802 IsContained = true;
7803 return ContainedRD;
7804 }
7805 }
7806
7807 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007808}
7809
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007810/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007811/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007812static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007813 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007814 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007815 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007816 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007817
Craig Topperc3ec1492014-05-26 06:22:03 +00007818 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007819}
7820
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007821/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007822static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007823 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7824 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007825 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007826 return SizeOf->getTypeOfArgument();
7827
7828 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007829}
7830
Akira Hatanaka2be04412018-04-17 19:13:41 +00007831namespace {
7832
7833struct SearchNonTrivialToInitializeField
7834 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7835 using Super =
7836 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7837
7838 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7839
7840 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7841 SourceLocation SL) {
7842 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7843 asDerived().visitArray(PDIK, AT, SL);
7844 return;
7845 }
7846
7847 Super::visitWithKind(PDIK, FT, SL);
7848 }
7849
7850 void visitARCStrong(QualType FT, SourceLocation SL) {
7851 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7852 }
7853 void visitARCWeak(QualType FT, SourceLocation SL) {
7854 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7855 }
7856 void visitStruct(QualType FT, SourceLocation SL) {
7857 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7858 visit(FD->getType(), FD->getLocation());
7859 }
7860 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7861 const ArrayType *AT, SourceLocation SL) {
7862 visit(getContext().getBaseElementType(AT), SL);
7863 }
7864 void visitTrivial(QualType FT, SourceLocation SL) {}
7865
7866 static void diag(QualType RT, const Expr *E, Sema &S) {
7867 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7868 }
7869
7870 ASTContext &getContext() { return S.getASTContext(); }
7871
7872 const Expr *E;
7873 Sema &S;
7874};
7875
7876struct SearchNonTrivialToCopyField
7877 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7878 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7879
7880 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7881
7882 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7883 SourceLocation SL) {
7884 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7885 asDerived().visitArray(PCK, AT, SL);
7886 return;
7887 }
7888
7889 Super::visitWithKind(PCK, FT, SL);
7890 }
7891
7892 void visitARCStrong(QualType FT, SourceLocation SL) {
7893 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7894 }
7895 void visitARCWeak(QualType FT, SourceLocation SL) {
7896 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7897 }
7898 void visitStruct(QualType FT, SourceLocation SL) {
7899 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7900 visit(FD->getType(), FD->getLocation());
7901 }
7902 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7903 SourceLocation SL) {
7904 visit(getContext().getBaseElementType(AT), SL);
7905 }
7906 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7907 SourceLocation SL) {}
7908 void visitTrivial(QualType FT, SourceLocation SL) {}
7909 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7910
7911 static void diag(QualType RT, const Expr *E, Sema &S) {
7912 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7913 }
7914
7915 ASTContext &getContext() { return S.getASTContext(); }
7916
7917 const Expr *E;
7918 Sema &S;
7919};
7920
7921}
7922
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007923/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007924///
Chandler Carruthac687262011-06-03 06:23:57 +00007925/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007926/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7927/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007928///
7929/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007930void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007931 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007932 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007933 assert(BId != 0);
7934
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007935 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007936 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007937 unsigned ExpectedNumArgs =
7938 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007939 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007940 return;
7941
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007942 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007943 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007944 unsigned LenArg =
7945 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007946 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007947
Nico Weber0e6daef2013-12-26 23:38:39 +00007948 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7949 Call->getLocStart(), Call->getRParenLoc()))
7950 return;
7951
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007952 // We have special checking when the length is a sizeof expression.
7953 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7954 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7955 llvm::FoldingSetNodeID SizeOfArgID;
7956
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007957 // Although widely used, 'bzero' is not a standard function. Be more strict
7958 // with the argument types before allowing diagnostics and only allow the
7959 // form bzero(ptr, sizeof(...)).
7960 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7961 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7962 return;
7963
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007964 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7965 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007966 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007967
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007968 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007969 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007970 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007971 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007972
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007973 // Never warn about void type pointers. This can be used to suppress
7974 // false positives.
7975 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007976 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007977
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007978 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7979 // actually comparing the expressions for equality. Because computing the
7980 // expression IDs can be expensive, we only do this if the diagnostic is
7981 // enabled.
7982 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007983 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7984 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007985 // We only compute IDs for expressions if the warning is enabled, and
7986 // cache the sizeof arg's ID.
7987 if (SizeOfArgID == llvm::FoldingSetNodeID())
7988 SizeOfArg->Profile(SizeOfArgID, Context, true);
7989 llvm::FoldingSetNodeID DestID;
7990 Dest->Profile(DestID, Context, true);
7991 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007992 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7993 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007994 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007995 StringRef ReadableName = FnName->getName();
7996
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007997 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007998 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007999 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00008000 if (!PointeeTy->isIncompleteType() &&
8001 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008002 ActionIdx = 2; // If the pointee's size is sizeof(char),
8003 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00008004
8005 // If the function is defined as a builtin macro, do not show macro
8006 // expansion.
8007 SourceLocation SL = SizeOfArg->getExprLoc();
8008 SourceRange DSR = Dest->getSourceRange();
8009 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008010 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00008011
8012 if (SM.isMacroArgExpansion(SL)) {
8013 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8014 SL = SM.getSpellingLoc(SL);
8015 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8016 SM.getSpellingLoc(DSR.getEnd()));
8017 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8018 SM.getSpellingLoc(SSR.getEnd()));
8019 }
8020
Anna Zaksd08d9152012-05-30 23:14:52 +00008021 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008022 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00008023 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00008024 << PointeeTy
8025 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00008026 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00008027 << SSR);
8028 DiagRuntimeBehavior(SL, SizeOfArg,
8029 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8030 << ActionIdx
8031 << SSR);
8032
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008033 break;
8034 }
8035 }
8036
8037 // Also check for cases where the sizeof argument is the exact same
8038 // type as the memory argument, and where it points to a user-defined
8039 // record type.
8040 if (SizeOfArgTy != QualType()) {
8041 if (PointeeTy->isRecordType() &&
8042 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8043 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8044 PDiag(diag::warn_sizeof_pointer_type_memaccess)
8045 << FnName << SizeOfArgTy << ArgIdx
8046 << PointeeTy << Dest->getSourceRange()
8047 << LenExpr->getSourceRange());
8048 break;
8049 }
Nico Weberc5e73862011-06-14 16:14:58 +00008050 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00008051 } else if (DestTy->isArrayType()) {
8052 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00008053 }
Nico Weberc5e73862011-06-14 16:14:58 +00008054
Nico Weberc44b35e2015-03-21 17:37:46 +00008055 if (PointeeTy == QualType())
8056 continue;
Anna Zaks22122702012-01-17 00:37:07 +00008057
Nico Weberc44b35e2015-03-21 17:37:46 +00008058 // Always complain about dynamic classes.
8059 bool IsContained;
8060 if (const CXXRecordDecl *ContainedRD =
8061 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00008062
Nico Weberc44b35e2015-03-21 17:37:46 +00008063 unsigned OperationType = 0;
8064 // "overwritten" if we're warning about the destination for any call
8065 // but memcmp; otherwise a verb appropriate to the call.
8066 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
8067 if (BId == Builtin::BImemcpy)
8068 OperationType = 1;
8069 else if(BId == Builtin::BImemmove)
8070 OperationType = 2;
8071 else if (BId == Builtin::BImemcmp)
8072 OperationType = 3;
8073 }
8074
John McCall31168b02011-06-15 23:02:42 +00008075 DiagRuntimeBehavior(
8076 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00008077 PDiag(diag::warn_dyn_class_memaccess)
8078 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
8079 << FnName << IsContained << ContainedRD << OperationType
8080 << Call->getCallee()->getSourceRange());
8081 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8082 BId != Builtin::BImemset)
8083 DiagRuntimeBehavior(
8084 Dest->getExprLoc(), Dest,
8085 PDiag(diag::warn_arc_object_memaccess)
8086 << ArgIdx << FnName << PointeeTy
8087 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00008088 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8089 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8090 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8091 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8092 PDiag(diag::warn_cstruct_memaccess)
8093 << ArgIdx << FnName << PointeeTy << 0);
8094 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8095 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8096 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8097 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8098 PDiag(diag::warn_cstruct_memaccess)
8099 << ArgIdx << FnName << PointeeTy << 1);
8100 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8101 } else {
8102 continue;
8103 }
8104 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00008105 continue;
8106
8107 DiagRuntimeBehavior(
8108 Dest->getExprLoc(), Dest,
8109 PDiag(diag::note_bad_memaccess_silence)
8110 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8111 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008112 }
8113}
8114
Ted Kremenek6865f772011-08-18 20:55:45 +00008115// A little helper routine: ignore addition and subtraction of integer literals.
8116// This intentionally does not ignore all integer constant expressions because
8117// we don't want to remove sizeof().
8118static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8119 Ex = Ex->IgnoreParenCasts();
8120
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008121 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00008122 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8123 if (!BO || !BO->isAdditiveOp())
8124 break;
8125
8126 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8127 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8128
8129 if (isa<IntegerLiteral>(RHS))
8130 Ex = LHS;
8131 else if (isa<IntegerLiteral>(LHS))
8132 Ex = RHS;
8133 else
8134 break;
8135 }
8136
8137 return Ex;
8138}
8139
Anna Zaks13b08572012-08-08 21:42:23 +00008140static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8141 ASTContext &Context) {
8142 // Only handle constant-sized or VLAs, but not flexible members.
8143 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8144 // Only issue the FIXIT for arrays of size > 1.
8145 if (CAT->getSize().getSExtValue() <= 1)
8146 return false;
8147 } else if (!Ty->isVariableArrayType()) {
8148 return false;
8149 }
8150 return true;
8151}
8152
Ted Kremenek6865f772011-08-18 20:55:45 +00008153// Warn if the user has made the 'size' argument to strlcpy or strlcat
8154// be the size of the source, instead of the destination.
8155void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8156 IdentifierInfo *FnName) {
8157
8158 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00008159 unsigned NumArgs = Call->getNumArgs();
8160 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00008161 return;
8162
8163 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8164 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00008165 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00008166
8167 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8168 Call->getLocStart(), Call->getRParenLoc()))
8169 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008170
8171 // Look for 'strlcpy(dst, x, sizeof(x))'
8172 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8173 CompareWithSrc = Ex;
8174 else {
8175 // Look for 'strlcpy(dst, x, strlen(x))'
8176 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008177 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8178 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008179 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8180 }
8181 }
8182
8183 if (!CompareWithSrc)
8184 return;
8185
8186 // Determine if the argument to sizeof/strlen is equal to the source
8187 // argument. In principle there's all kinds of things you could do
8188 // here, for instance creating an == expression and evaluating it with
8189 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8190 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8191 if (!SrcArgDRE)
8192 return;
8193
8194 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8195 if (!CompareWithSrcDRE ||
8196 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8197 return;
8198
8199 const Expr *OriginalSizeArg = Call->getArg(2);
8200 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8201 << OriginalSizeArg->getSourceRange() << FnName;
8202
8203 // Output a FIXIT hint if the destination is an array (rather than a
8204 // pointer to an array). This could be enhanced to handle some
8205 // pointers if we know the actual size, like if DstArg is 'array+2'
8206 // we could say 'sizeof(array)-2'.
8207 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008208 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008209 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008210
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008211 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008212 llvm::raw_svector_ostream OS(sizeString);
8213 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008214 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008215 OS << ")";
8216
8217 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8218 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8219 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008220}
8221
Anna Zaks314cd092012-02-01 19:08:57 +00008222/// Check if two expressions refer to the same declaration.
8223static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8224 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8225 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8226 return D1->getDecl() == D2->getDecl();
8227 return false;
8228}
8229
8230static const Expr *getStrlenExprArg(const Expr *E) {
8231 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8232 const FunctionDecl *FD = CE->getDirectCallee();
8233 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008234 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008235 return CE->getArg(0)->IgnoreParenCasts();
8236 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008237 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008238}
8239
8240// Warn on anti-patterns as the 'size' argument to strncat.
8241// The correct size argument should look like following:
8242// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8243void Sema::CheckStrncatArguments(const CallExpr *CE,
8244 IdentifierInfo *FnName) {
8245 // Don't crash if the user has the wrong number of arguments.
8246 if (CE->getNumArgs() < 3)
8247 return;
8248 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8249 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8250 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8251
Nico Weber0e6daef2013-12-26 23:38:39 +00008252 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8253 CE->getRParenLoc()))
8254 return;
8255
Anna Zaks314cd092012-02-01 19:08:57 +00008256 // Identify common expressions, which are wrongly used as the size argument
8257 // to strncat and may lead to buffer overflows.
8258 unsigned PatternType = 0;
8259 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8260 // - sizeof(dst)
8261 if (referToTheSameDecl(SizeOfArg, DstArg))
8262 PatternType = 1;
8263 // - sizeof(src)
8264 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8265 PatternType = 2;
8266 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8267 if (BE->getOpcode() == BO_Sub) {
8268 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8269 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8270 // - sizeof(dst) - strlen(dst)
8271 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8272 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8273 PatternType = 1;
8274 // - sizeof(src) - (anything)
8275 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8276 PatternType = 2;
8277 }
8278 }
8279
8280 if (PatternType == 0)
8281 return;
8282
Anna Zaks5069aa32012-02-03 01:27:37 +00008283 // Generate the diagnostic.
8284 SourceLocation SL = LenArg->getLocStart();
8285 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008286 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008287
8288 // If the function is defined as a builtin macro, do not show macro expansion.
8289 if (SM.isMacroArgExpansion(SL)) {
8290 SL = SM.getSpellingLoc(SL);
8291 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8292 SM.getSpellingLoc(SR.getEnd()));
8293 }
8294
Anna Zaks13b08572012-08-08 21:42:23 +00008295 // Check if the destination is an array (rather than a pointer to an array).
8296 QualType DstTy = DstArg->getType();
8297 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8298 Context);
8299 if (!isKnownSizeArray) {
8300 if (PatternType == 1)
8301 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8302 else
8303 Diag(SL, diag::warn_strncat_src_size) << SR;
8304 return;
8305 }
8306
Anna Zaks314cd092012-02-01 19:08:57 +00008307 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008308 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008309 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008310 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008311
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008312 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008313 llvm::raw_svector_ostream OS(sizeString);
8314 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008315 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008316 OS << ") - ";
8317 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008318 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008319 OS << ") - 1";
8320
Anna Zaks5069aa32012-02-03 01:27:37 +00008321 Diag(SL, diag::note_strncat_wrong_size)
8322 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008323}
8324
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008325//===--- CHECK: Return Address of Stack Variable --------------------------===//
8326
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008327static const Expr *EvalVal(const Expr *E,
8328 SmallVectorImpl<const DeclRefExpr *> &refVars,
8329 const Decl *ParentDecl);
8330static const Expr *EvalAddr(const Expr *E,
8331 SmallVectorImpl<const DeclRefExpr *> &refVars,
8332 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008333
8334/// CheckReturnStackAddr - Check if a return statement returns the address
8335/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008336static void
8337CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8338 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008339 const Expr *stackE = nullptr;
8340 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008341
8342 // Perform checking for returned stack addresses, local blocks,
8343 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008344 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008345 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008346 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008347 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008348 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008349 }
8350
Craig Topperc3ec1492014-05-26 06:22:03 +00008351 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008352 return; // Nothing suspicious was found.
8353
Simon Pilgrim750bde62017-03-31 11:00:53 +00008354 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008355 // of a parameter reference doesn't need a warning.
8356 for (auto *DRE : refVars)
8357 if (isa<ParmVarDecl>(DRE->getDecl()))
8358 return;
8359
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008360 SourceLocation diagLoc;
8361 SourceRange diagRange;
8362 if (refVars.empty()) {
8363 diagLoc = stackE->getLocStart();
8364 diagRange = stackE->getSourceRange();
8365 } else {
8366 // We followed through a reference variable. 'stackE' contains the
8367 // problematic expression but we will warn at the return statement pointing
8368 // at the reference variable. We will later display the "trail" of
8369 // reference variables using notes.
8370 diagLoc = refVars[0]->getLocStart();
8371 diagRange = refVars[0]->getSourceRange();
8372 }
8373
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008374 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8375 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008376 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008377 << DR->getDecl()->getDeclName() << diagRange;
8378 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008379 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008380 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008381 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008382 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008383 // If there is an LValue->RValue conversion, then the value of the
8384 // reference type is used, not the reference.
8385 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8386 if (ICE->getCastKind() == CK_LValueToRValue) {
8387 return;
8388 }
8389 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008390 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8391 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008392 }
8393
8394 // Display the "trail" of reference variables that we followed until we
8395 // found the problematic expression using notes.
8396 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008397 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008398 // If this var binds to another reference var, show the range of the next
8399 // var, otherwise the var binds to the problematic expression, in which case
8400 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008401 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8402 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008403 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8404 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008405 }
8406}
8407
8408/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8409/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008410/// to a location on the stack, a local block, an address of a label, or a
8411/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008412/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008413/// encounter a subexpression that (1) clearly does not lead to one of the
8414/// above problematic expressions (2) is something we cannot determine leads to
8415/// a problematic expression based on such local checking.
8416///
8417/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8418/// the expression that they point to. Such variables are added to the
8419/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008420///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008421/// EvalAddr processes expressions that are pointers that are used as
8422/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008423/// At the base case of the recursion is a check for the above problematic
8424/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008425///
8426/// This implementation handles:
8427///
8428/// * pointer-to-pointer casts
8429/// * implicit conversions from array references to pointers
8430/// * taking the address of fields
8431/// * arbitrary interplay between "&" and "*" operators
8432/// * pointer arithmetic from an address of a stack variable
8433/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008434static const Expr *EvalAddr(const Expr *E,
8435 SmallVectorImpl<const DeclRefExpr *> &refVars,
8436 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008437 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008438 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008439
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008440 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008441 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008442 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008443 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008444 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008445
Peter Collingbourne91147592011-04-15 00:35:48 +00008446 E = E->IgnoreParens();
8447
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008448 // Our "symbolic interpreter" is just a dispatch off the currently
8449 // viewed AST node. We then recursively traverse the AST by calling
8450 // EvalAddr and EvalVal appropriately.
8451 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008452 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008453 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008454
Richard Smith40f08eb2014-01-30 22:05:38 +00008455 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008456 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008457 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008458
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008459 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008460 // If this is a reference variable, follow through to the expression that
8461 // it points to.
8462 if (V->hasLocalStorage() &&
8463 V->getType()->isReferenceType() && V->hasInit()) {
8464 // Add the reference variable to the "trail".
8465 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008466 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008467 }
8468
Craig Topperc3ec1492014-05-26 06:22:03 +00008469 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008470 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008471
Chris Lattner934edb22007-12-28 05:31:15 +00008472 case Stmt::UnaryOperatorClass: {
8473 // The only unary operator that make sense to handle here
8474 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008475 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008476
John McCalle3027922010-08-25 11:45:40 +00008477 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008478 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008479 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008480 }
Mike Stump11289f42009-09-09 15:08:12 +00008481
Chris Lattner934edb22007-12-28 05:31:15 +00008482 case Stmt::BinaryOperatorClass: {
8483 // Handle pointer arithmetic. All other binary operators are not valid
8484 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008485 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008486 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008487
John McCalle3027922010-08-25 11:45:40 +00008488 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008489 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008490
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008491 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008492
8493 // Determine which argument is the real pointer base. It could be
8494 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008495 if (!Base->getType()->isPointerType())
8496 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008497
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008498 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008499 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008500 }
Steve Naroff2752a172008-09-10 19:17:48 +00008501
Chris Lattner934edb22007-12-28 05:31:15 +00008502 // For conditional operators we need to see if either the LHS or RHS are
8503 // valid DeclRefExpr*s. If one of them is valid, we return it.
8504 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008505 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008506
Chris Lattner934edb22007-12-28 05:31:15 +00008507 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008508 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008509 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008510 // In C++, we can have a throw-expression, which has 'void' type.
8511 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008512 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008513 return LHS;
8514 }
Chris Lattner934edb22007-12-28 05:31:15 +00008515
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008516 // In C++, we can have a throw-expression, which has 'void' type.
8517 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008518 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008519
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008520 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008521 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008522
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008523 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008524 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008525 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008526 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008527
8528 case Stmt::AddrLabelExprClass:
8529 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008530
John McCall28fc7092011-11-10 05:35:25 +00008531 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008532 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8533 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008534
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008535 // For casts, we need to handle conversions from arrays to
8536 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008537 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008538 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008539 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008540 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008541 case Stmt::CXXStaticCastExprClass:
8542 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008543 case Stmt::CXXConstCastExprClass:
8544 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008545 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008546 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008547 case CK_LValueToRValue:
8548 case CK_NoOp:
8549 case CK_BaseToDerived:
8550 case CK_DerivedToBase:
8551 case CK_UncheckedDerivedToBase:
8552 case CK_Dynamic:
8553 case CK_CPointerToObjCPointerCast:
8554 case CK_BlockPointerToObjCPointerCast:
8555 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008556 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008557
8558 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008559 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008560
Richard Trieudadefde2014-07-02 04:39:38 +00008561 case CK_BitCast:
8562 if (SubExpr->getType()->isAnyPointerType() ||
8563 SubExpr->getType()->isBlockPointerType() ||
8564 SubExpr->getType()->isObjCQualifiedIdType())
8565 return EvalAddr(SubExpr, refVars, ParentDecl);
8566 else
8567 return nullptr;
8568
Eli Friedman8195ad72012-02-23 23:04:32 +00008569 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008570 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008571 }
Chris Lattner934edb22007-12-28 05:31:15 +00008572 }
Mike Stump11289f42009-09-09 15:08:12 +00008573
Douglas Gregorfe314812011-06-21 17:03:29 +00008574 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008575 if (const Expr *Result =
8576 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8577 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008578 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008579 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008580
Chris Lattner934edb22007-12-28 05:31:15 +00008581 // Everything else: we simply don't reason about them.
8582 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008583 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008584 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008585}
Mike Stump11289f42009-09-09 15:08:12 +00008586
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008587/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8588/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008589static const Expr *EvalVal(const Expr *E,
8590 SmallVectorImpl<const DeclRefExpr *> &refVars,
8591 const Decl *ParentDecl) {
8592 do {
8593 // We should only be called for evaluating non-pointer expressions, or
8594 // expressions with a pointer type that are not used as references but
8595 // instead
8596 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008597
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008598 // Our "symbolic interpreter" is just a dispatch off the currently
8599 // viewed AST node. We then recursively traverse the AST by calling
8600 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008601
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008602 E = E->IgnoreParens();
8603 switch (E->getStmtClass()) {
8604 case Stmt::ImplicitCastExprClass: {
8605 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8606 if (IE->getValueKind() == VK_LValue) {
8607 E = IE->getSubExpr();
8608 continue;
8609 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008610 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008611 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008612
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008613 case Stmt::ExprWithCleanupsClass:
8614 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8615 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008616
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008617 case Stmt::DeclRefExprClass: {
8618 // When we hit a DeclRefExpr we are looking at code that refers to a
8619 // variable's name. If it's not a reference variable we check if it has
8620 // local storage within the function, and if so, return the expression.
8621 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8622
8623 // If we leave the immediate function, the lifetime isn't about to end.
8624 if (DR->refersToEnclosingVariableOrCapture())
8625 return nullptr;
8626
8627 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8628 // Check if it refers to itself, e.g. "int& i = i;".
8629 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008630 return DR;
8631
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008632 if (V->hasLocalStorage()) {
8633 if (!V->getType()->isReferenceType())
8634 return DR;
8635
8636 // Reference variable, follow through to the expression that
8637 // it points to.
8638 if (V->hasInit()) {
8639 // Add the reference variable to the "trail".
8640 refVars.push_back(DR);
8641 return EvalVal(V->getInit(), refVars, V);
8642 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008643 }
8644 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008645
8646 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008647 }
Mike Stump11289f42009-09-09 15:08:12 +00008648
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008649 case Stmt::UnaryOperatorClass: {
8650 // The only unary operator that make sense to handle here
8651 // is Deref. All others don't resolve to a "name." This includes
8652 // handling all sorts of rvalues passed to a unary operator.
8653 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008654
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008655 if (U->getOpcode() == UO_Deref)
8656 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008657
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008658 return nullptr;
8659 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008660
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008661 case Stmt::ArraySubscriptExprClass: {
8662 // Array subscripts are potential references to data on the stack. We
8663 // retrieve the DeclRefExpr* for the array variable if it indeed
8664 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008665 const auto *ASE = cast<ArraySubscriptExpr>(E);
8666 if (ASE->isTypeDependent())
8667 return nullptr;
8668 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008669 }
Mike Stump11289f42009-09-09 15:08:12 +00008670
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008671 case Stmt::OMPArraySectionExprClass: {
8672 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8673 ParentDecl);
8674 }
Mike Stump11289f42009-09-09 15:08:12 +00008675
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008676 case Stmt::ConditionalOperatorClass: {
8677 // For conditional operators we need to see if either the LHS or RHS are
8678 // non-NULL Expr's. If one is non-NULL, we return it.
8679 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008680
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008681 // Handle the GNU extension for missing LHS.
8682 if (const Expr *LHSExpr = C->getLHS()) {
8683 // In C++, we can have a throw-expression, which has 'void' type.
8684 if (!LHSExpr->getType()->isVoidType())
8685 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8686 return LHS;
8687 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008688
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008689 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008690 if (C->getRHS()->getType()->isVoidType())
8691 return nullptr;
8692
8693 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008694 }
8695
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008696 // Accesses to members are potential references to data on the stack.
8697 case Stmt::MemberExprClass: {
8698 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008699
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008700 // Check for indirect access. We only want direct field accesses.
8701 if (M->isArrow())
8702 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008703
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008704 // Check whether the member type is itself a reference, in which case
8705 // we're not going to refer to the member, but to what the member refers
8706 // to.
8707 if (M->getMemberDecl()->getType()->isReferenceType())
8708 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008709
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008710 return EvalVal(M->getBase(), refVars, ParentDecl);
8711 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008712
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008713 case Stmt::MaterializeTemporaryExprClass:
8714 if (const Expr *Result =
8715 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8716 refVars, ParentDecl))
8717 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008718 return E;
8719
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008720 default:
8721 // Check that we don't return or take the address of a reference to a
8722 // temporary. This is only useful in C++.
8723 if (!E->isTypeDependent() && E->isRValue())
8724 return E;
8725
8726 // Everything else: we simply don't reason about them.
8727 return nullptr;
8728 }
8729 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008730}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008731
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008732void
8733Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8734 SourceLocation ReturnLoc,
8735 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008736 const AttrVec *Attrs,
8737 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008738 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8739
8740 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008741 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8742 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008743 CheckNonNullExpr(*this, RetValExp))
8744 Diag(ReturnLoc, diag::warn_null_ret)
8745 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008746
8747 // C++11 [basic.stc.dynamic.allocation]p4:
8748 // If an allocation function declared with a non-throwing
8749 // exception-specification fails to allocate storage, it shall return
8750 // a null pointer. Any other allocation function that fails to allocate
8751 // storage shall indicate failure only by throwing an exception [...]
8752 if (FD) {
8753 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8754 if (Op == OO_New || Op == OO_Array_New) {
8755 const FunctionProtoType *Proto
8756 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008757 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008758 CheckNonNullExpr(*this, RetValExp))
8759 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8760 << FD << getLangOpts().CPlusPlus11;
8761 }
8762 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008763}
8764
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008765//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8766
8767/// Check for comparisons of floating point operands using != and ==.
8768/// Issue a warning if these are no self-comparisons, as they are not likely
8769/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008770void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008771 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8772 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008773
8774 // Special case: check for x == x (which is OK).
8775 // Do not emit warnings for such cases.
8776 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8777 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8778 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008779 return;
Mike Stump11289f42009-09-09 15:08:12 +00008780
Ted Kremenekeda40e22007-11-29 00:59:04 +00008781 // Special case: check for comparisons against literals that can be exactly
8782 // represented by APFloat. In such cases, do not emit a warning. This
8783 // is a heuristic: often comparison against such literals are used to
8784 // detect if a value in a variable has not changed. This clearly can
8785 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008786 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8787 if (FLL->isExact())
8788 return;
8789 } else
8790 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8791 if (FLR->isExact())
8792 return;
Mike Stump11289f42009-09-09 15:08:12 +00008793
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008794 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008795 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008796 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008797 return;
Mike Stump11289f42009-09-09 15:08:12 +00008798
David Blaikie1f4ff152012-07-16 20:47:22 +00008799 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008800 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008801 return;
Mike Stump11289f42009-09-09 15:08:12 +00008802
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008803 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008804 Diag(Loc, diag::warn_floatingpoint_eq)
8805 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008806}
John McCallca01b222010-01-04 23:21:16 +00008807
John McCall70aa5392010-01-06 05:24:50 +00008808//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8809//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008810
John McCall70aa5392010-01-06 05:24:50 +00008811namespace {
John McCallca01b222010-01-04 23:21:16 +00008812
John McCall70aa5392010-01-06 05:24:50 +00008813/// Structure recording the 'active' range of an integer-valued
8814/// expression.
8815struct IntRange {
8816 /// The number of bits active in the int.
8817 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008818
John McCall70aa5392010-01-06 05:24:50 +00008819 /// True if the int is known not to have negative values.
8820 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008821
John McCall70aa5392010-01-06 05:24:50 +00008822 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008823 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008824
John McCall817d4af2010-11-10 23:38:19 +00008825 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008826 static IntRange forBoolType() {
8827 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008828 }
8829
John McCall817d4af2010-11-10 23:38:19 +00008830 /// Returns the range of an opaque value of the given integral type.
8831 static IntRange forValueOfType(ASTContext &C, QualType T) {
8832 return forValueOfCanonicalType(C,
8833 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008834 }
8835
John McCall817d4af2010-11-10 23:38:19 +00008836 /// Returns the range of an opaque value of a canonical integral type.
8837 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008838 assert(T->isCanonicalUnqualified());
8839
8840 if (const VectorType *VT = dyn_cast<VectorType>(T))
8841 T = VT->getElementType().getTypePtr();
8842 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8843 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008844 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8845 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008846
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008847 if (!C.getLangOpts().CPlusPlus) {
8848 // For enum types in C code, use the underlying datatype.
8849 if (const EnumType *ET = dyn_cast<EnumType>(T))
8850 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8851 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8852 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008853 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008854 // In C++11, enums can have a fixed underlying type. Use this type to
8855 // compute the range.
8856 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008857 return IntRange(C.getIntWidth(QualType(T, 0)),
8858 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008859 }
John McCall18a2c2c2010-11-09 22:22:12 +00008860
David Majnemer6a426652013-06-07 22:07:20 +00008861 unsigned NumPositive = Enum->getNumPositiveBits();
8862 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008863
David Majnemer6a426652013-06-07 22:07:20 +00008864 if (NumNegative == 0)
8865 return IntRange(NumPositive, true/*NonNegative*/);
8866 else
8867 return IntRange(std::max(NumPositive + 1, NumNegative),
8868 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008869 }
John McCall70aa5392010-01-06 05:24:50 +00008870
8871 const BuiltinType *BT = cast<BuiltinType>(T);
8872 assert(BT->isInteger());
8873
8874 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8875 }
8876
John McCall817d4af2010-11-10 23:38:19 +00008877 /// Returns the "target" range of a canonical integral type, i.e.
8878 /// the range of values expressible in the type.
8879 ///
8880 /// This matches forValueOfCanonicalType except that enums have the
8881 /// full range of their type, not the range of their enumerators.
8882 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8883 assert(T->isCanonicalUnqualified());
8884
8885 if (const VectorType *VT = dyn_cast<VectorType>(T))
8886 T = VT->getElementType().getTypePtr();
8887 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8888 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008889 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8890 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008891 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008892 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008893
8894 const BuiltinType *BT = cast<BuiltinType>(T);
8895 assert(BT->isInteger());
8896
8897 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8898 }
8899
8900 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008901 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008902 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008903 L.NonNegative && R.NonNegative);
8904 }
8905
John McCall817d4af2010-11-10 23:38:19 +00008906 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008907 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008908 return IntRange(std::min(L.Width, R.Width),
8909 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008910 }
8911};
8912
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008913} // namespace
8914
8915static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8916 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008917 if (value.isSigned() && value.isNegative())
8918 return IntRange(value.getMinSignedBits(), false);
8919
8920 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008921 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008922
8923 // isNonNegative() just checks the sign bit without considering
8924 // signedness.
8925 return IntRange(value.getActiveBits(), true);
8926}
8927
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008928static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8929 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008930 if (result.isInt())
8931 return GetValueRange(C, result.getInt(), MaxWidth);
8932
8933 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008934 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8935 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8936 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8937 R = IntRange::join(R, El);
8938 }
John McCall70aa5392010-01-06 05:24:50 +00008939 return R;
8940 }
8941
8942 if (result.isComplexInt()) {
8943 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8944 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8945 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008946 }
8947
8948 // This can happen with lossless casts to intptr_t of "based" lvalues.
8949 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008950 // FIXME: The only reason we need to pass the type in here is to get
8951 // the sign right on this one case. It would be nice if APValue
8952 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008953 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008954 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008955}
John McCall70aa5392010-01-06 05:24:50 +00008956
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008957static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008958 QualType Ty = E->getType();
8959 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8960 Ty = AtomicRHS->getValueType();
8961 return Ty;
8962}
8963
John McCall70aa5392010-01-06 05:24:50 +00008964/// Pseudo-evaluate the given integer expression, estimating the
8965/// range of values it might take.
8966///
8967/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008968static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008969 E = E->IgnoreParens();
8970
8971 // Try a full evaluation first.
8972 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008973 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008974 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008975
8976 // I think we only want to look through implicit casts here; if the
8977 // user has an explicit widening cast, we should treat the value as
8978 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008979 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008980 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008981 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8982
Eli Friedmane6d33952013-07-08 20:20:06 +00008983 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008984
George Burgess IVdf1ed002016-01-13 01:52:39 +00008985 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8986 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008987
John McCall70aa5392010-01-06 05:24:50 +00008988 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008989 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008990 return OutputTypeRange;
8991
8992 IntRange SubRange
8993 = GetExprRange(C, CE->getSubExpr(),
8994 std::min(MaxWidth, OutputTypeRange.Width));
8995
8996 // Bail out if the subexpr's range is as wide as the cast type.
8997 if (SubRange.Width >= OutputTypeRange.Width)
8998 return OutputTypeRange;
8999
9000 // Otherwise, we take the smaller width, and we're non-negative if
9001 // either the output type or the subexpr is.
9002 return IntRange(SubRange.Width,
9003 SubRange.NonNegative || OutputTypeRange.NonNegative);
9004 }
9005
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009006 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009007 // If we can fold the condition, just take that operand.
9008 bool CondResult;
9009 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9010 return GetExprRange(C, CondResult ? CO->getTrueExpr()
9011 : CO->getFalseExpr(),
9012 MaxWidth);
9013
9014 // Otherwise, conservatively merge.
9015 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9016 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9017 return IntRange::join(L, R);
9018 }
9019
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009020 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009021 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00009022 case BO_Cmp:
9023 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00009024
9025 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00009026 case BO_LAnd:
9027 case BO_LOr:
9028 case BO_LT:
9029 case BO_GT:
9030 case BO_LE:
9031 case BO_GE:
9032 case BO_EQ:
9033 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009034 return IntRange::forBoolType();
9035
John McCallc3688382011-07-13 06:35:24 +00009036 // The type of the assignments is the type of the LHS, so the RHS
9037 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009038 case BO_MulAssign:
9039 case BO_DivAssign:
9040 case BO_RemAssign:
9041 case BO_AddAssign:
9042 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009043 case BO_XorAssign:
9044 case BO_OrAssign:
9045 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009046 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009047
John McCallc3688382011-07-13 06:35:24 +00009048 // Simple assignments just pass through the RHS, which will have
9049 // been coerced to the LHS type.
9050 case BO_Assign:
9051 // TODO: bitfields?
9052 return GetExprRange(C, BO->getRHS(), MaxWidth);
9053
John McCall70aa5392010-01-06 05:24:50 +00009054 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009055 case BO_PtrMemD:
9056 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009057 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009058
John McCall2ce81ad2010-01-06 22:07:33 +00009059 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009060 case BO_And:
9061 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009062 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9063 GetExprRange(C, BO->getRHS(), MaxWidth));
9064
John McCall70aa5392010-01-06 05:24:50 +00009065 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00009066 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00009067 // ...except that we want to treat '1 << (blah)' as logically
9068 // positive. It's an important idiom.
9069 if (IntegerLiteral *I
9070 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9071 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009072 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00009073 return IntRange(R.Width, /*NonNegative*/ true);
9074 }
9075 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009076 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00009077
John McCalle3027922010-08-25 11:45:40 +00009078 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00009079 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009080
John McCall2ce81ad2010-01-06 22:07:33 +00009081 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009082 case BO_Shr:
9083 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009084 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9085
9086 // If the shift amount is a positive constant, drop the width by
9087 // that much.
9088 llvm::APSInt shift;
9089 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9090 shift.isNonNegative()) {
9091 unsigned zext = shift.getZExtValue();
9092 if (zext >= L.Width)
9093 L.Width = (L.NonNegative ? 0 : 1);
9094 else
9095 L.Width -= zext;
9096 }
9097
9098 return L;
9099 }
9100
9101 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009102 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009103 return GetExprRange(C, BO->getRHS(), MaxWidth);
9104
John McCall2ce81ad2010-01-06 22:07:33 +00009105 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009106 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009107 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009108 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009109 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009110
John McCall51431812011-07-14 22:39:48 +00009111 // The width of a division result is mostly determined by the size
9112 // of the LHS.
9113 case BO_Div: {
9114 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009115 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009116 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9117
9118 // If the divisor is constant, use that.
9119 llvm::APSInt divisor;
9120 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9121 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9122 if (log2 >= L.Width)
9123 L.Width = (L.NonNegative ? 0 : 1);
9124 else
9125 L.Width = std::min(L.Width - log2, MaxWidth);
9126 return L;
9127 }
9128
9129 // Otherwise, just use the LHS's width.
9130 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9131 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9132 }
9133
9134 // The result of a remainder can't be larger than the result of
9135 // either side.
9136 case BO_Rem: {
9137 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009138 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009139 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9140 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9141
9142 IntRange meet = IntRange::meet(L, R);
9143 meet.Width = std::min(meet.Width, MaxWidth);
9144 return meet;
9145 }
9146
9147 // The default behavior is okay for these.
9148 case BO_Mul:
9149 case BO_Add:
9150 case BO_Xor:
9151 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009152 break;
9153 }
9154
John McCall51431812011-07-14 22:39:48 +00009155 // The default case is to treat the operation as if it were closed
9156 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009157 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9158 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9159 return IntRange::join(L, R);
9160 }
9161
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009162 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009163 switch (UO->getOpcode()) {
9164 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009165 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009166 return IntRange::forBoolType();
9167
9168 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009169 case UO_Deref:
9170 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009171 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009172
9173 default:
9174 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9175 }
9176 }
9177
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009178 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009179 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9180
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009181 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009182 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009183 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009184
Eli Friedmane6d33952013-07-08 20:20:06 +00009185 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009186}
John McCall263a48b2010-01-04 23:31:57 +00009187
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009188static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009189 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009190}
9191
John McCall263a48b2010-01-04 23:31:57 +00009192/// Checks whether the given value, which currently has the given
9193/// source semantics, has the same value when coerced through the
9194/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009195static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9196 const llvm::fltSemantics &Src,
9197 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009198 llvm::APFloat truncated = value;
9199
9200 bool ignored;
9201 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9202 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9203
9204 return truncated.bitwiseIsEqual(value);
9205}
9206
9207/// Checks whether the given value, which currently has the given
9208/// source semantics, has the same value when coerced through the
9209/// target semantics.
9210///
9211/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009212static bool IsSameFloatAfterCast(const APValue &value,
9213 const llvm::fltSemantics &Src,
9214 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009215 if (value.isFloat())
9216 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9217
9218 if (value.isVector()) {
9219 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9220 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9221 return false;
9222 return true;
9223 }
9224
9225 assert(value.isComplexFloat());
9226 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9227 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9228}
9229
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009230static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009231
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009232static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009233 // Suppress cases where we are comparing against an enum constant.
9234 if (const DeclRefExpr *DR =
9235 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9236 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009237 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009238
9239 // Suppress cases where the '0' value is expanded from a macro.
9240 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009241 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009242
Roman Lebedev6de129e2017-10-15 20:13:17 +00009243 return false;
9244}
9245
Richard Smith692f66ab2017-12-06 19:23:19 +00009246static bool isKnownToHaveUnsignedValue(Expr *E) {
9247 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009248 (!E->getType()->isSignedIntegerType() ||
9249 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9250}
9251
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009252namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009253/// The promoted range of values of a type. In general this has the
9254/// following structure:
9255///
9256/// |-----------| . . . |-----------|
9257/// ^ ^ ^ ^
9258/// Min HoleMin HoleMax Max
9259///
9260/// ... where there is only a hole if a signed type is promoted to unsigned
9261/// (in which case Min and Max are the smallest and largest representable
9262/// values).
9263struct PromotedRange {
9264 // Min, or HoleMax if there is a hole.
9265 llvm::APSInt PromotedMin;
9266 // Max, or HoleMin if there is a hole.
9267 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009268
Richard Smitha5370fb2017-12-08 22:57:11 +00009269 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9270 if (R.Width == 0)
9271 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9272 else if (R.Width >= BitWidth && !Unsigned) {
9273 // Promotion made the type *narrower*. This happens when promoting
9274 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9275 // Treat all values of 'signed int' as being in range for now.
9276 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9277 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9278 } else {
9279 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9280 .extOrTrunc(BitWidth);
9281 PromotedMin.setIsUnsigned(Unsigned);
9282
9283 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9284 .extOrTrunc(BitWidth);
9285 PromotedMax.setIsUnsigned(Unsigned);
9286 }
9287 }
9288
9289 // Determine whether this range is contiguous (has no hole).
9290 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9291
9292 // Where a constant value is within the range.
9293 enum ComparisonResult {
9294 LT = 0x1,
9295 LE = 0x2,
9296 GT = 0x4,
9297 GE = 0x8,
9298 EQ = 0x10,
9299 NE = 0x20,
9300 InRangeFlag = 0x40,
9301
9302 Less = LE | LT | NE,
9303 Min = LE | InRangeFlag,
9304 InRange = InRangeFlag,
9305 Max = GE | InRangeFlag,
9306 Greater = GE | GT | NE,
9307
9308 OnlyValue = LE | GE | EQ | InRangeFlag,
9309 InHole = NE
9310 };
9311
9312 ComparisonResult compare(const llvm::APSInt &Value) const {
9313 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9314 Value.isUnsigned() == PromotedMin.isUnsigned());
9315 if (!isContiguous()) {
9316 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9317 if (Value.isMinValue()) return Min;
9318 if (Value.isMaxValue()) return Max;
9319 if (Value >= PromotedMin) return InRange;
9320 if (Value <= PromotedMax) return InRange;
9321 return InHole;
9322 }
9323
9324 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9325 case -1: return Less;
9326 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9327 case 1:
9328 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9329 case -1: return InRange;
9330 case 0: return Max;
9331 case 1: return Greater;
9332 }
9333 }
9334
9335 llvm_unreachable("impossible compare result");
9336 }
9337
Richard Smithc70f1d62017-12-14 15:16:18 +00009338 static llvm::Optional<StringRef>
9339 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9340 if (Op == BO_Cmp) {
9341 ComparisonResult LTFlag = LT, GTFlag = GT;
9342 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9343
9344 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9345 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9346 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9347 return llvm::None;
9348 }
9349
Richard Smitha5370fb2017-12-08 22:57:11 +00009350 ComparisonResult TrueFlag, FalseFlag;
9351 if (Op == BO_EQ) {
9352 TrueFlag = EQ;
9353 FalseFlag = NE;
9354 } else if (Op == BO_NE) {
9355 TrueFlag = NE;
9356 FalseFlag = EQ;
9357 } else {
9358 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9359 TrueFlag = LT;
9360 FalseFlag = GE;
9361 } else {
9362 TrueFlag = GT;
9363 FalseFlag = LE;
9364 }
9365 if (Op == BO_GE || Op == BO_LE)
9366 std::swap(TrueFlag, FalseFlag);
9367 }
9368 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009369 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009370 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009371 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009372 return llvm::None;
9373 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009374};
John McCallcc7e5bf2010-05-06 08:58:33 +00009375}
9376
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009377static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009378 // Strip off implicit integral promotions.
9379 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009380 if (ICE->getCastKind() != CK_IntegralCast &&
9381 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009382 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009383 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009384 }
9385
9386 return E->getType()->isEnumeralType();
9387}
9388
Richard Smith692f66ab2017-12-06 19:23:19 +00009389static int classifyConstantValue(Expr *Constant) {
9390 // The values of this enumeration are used in the diagnostics
9391 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9392 enum ConstantValueKind {
9393 Miscellaneous = 0,
9394 LiteralTrue,
9395 LiteralFalse
9396 };
9397 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9398 return BL->getValue() ? ConstantValueKind::LiteralTrue
9399 : ConstantValueKind::LiteralFalse;
9400 return ConstantValueKind::Miscellaneous;
9401}
9402
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009403static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9404 Expr *Constant, Expr *Other,
9405 const llvm::APSInt &Value,
9406 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009407 if (S.inTemplateInstantiation())
9408 return false;
9409
Richard Smitha5370fb2017-12-08 22:57:11 +00009410 Expr *OriginalOther = Other;
9411
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009412 Constant = Constant->IgnoreParenImpCasts();
9413 Other = Other->IgnoreParenImpCasts();
9414
Richard Smitha5370fb2017-12-08 22:57:11 +00009415 // Suppress warnings on tautological comparisons between values of the same
9416 // enumeration type. There are only two ways we could warn on this:
9417 // - If the constant is outside the range of representable values of
9418 // the enumeration. In such a case, we should warn about the cast
9419 // to enumeration type, not about the comparison.
9420 // - If the constant is the maximum / minimum in-range value. For an
9421 // enumeratin type, such comparisons can be meaningful and useful.
9422 if (Constant->getType()->isEnumeralType() &&
9423 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9424 return false;
9425
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009426 // TODO: Investigate using GetExprRange() to get tighter bounds
9427 // on the bit ranges.
9428 QualType OtherT = Other->getType();
9429 if (const auto *AT = OtherT->getAs<AtomicType>())
9430 OtherT = AT->getValueType();
9431 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9432
9433 // Whether we're treating Other as being a bool because of the form of
9434 // expression despite it having another type (typically 'int' in C).
9435 bool OtherIsBooleanDespiteType =
9436 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9437 if (OtherIsBooleanDespiteType)
9438 OtherRange = IntRange::forBoolType();
9439
Richard Smitha5370fb2017-12-08 22:57:11 +00009440 // Determine the promoted range of the other type and see if a comparison of
9441 // the constant against that range is tautological.
9442 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9443 Value.isUnsigned());
9444 auto Cmp = OtherPromotedRange.compare(Value);
9445 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9446 if (!Result)
9447 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009448
Richard Smitha5370fb2017-12-08 22:57:11 +00009449 // Suppress the diagnostic for an in-range comparison if the constant comes
9450 // from a macro or enumerator. We don't want to diagnose
9451 //
9452 // some_long_value <= INT_MAX
9453 //
9454 // when sizeof(int) == sizeof(long).
9455 bool InRange = Cmp & PromotedRange::InRangeFlag;
9456 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9457 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009458
9459 // If this is a comparison to an enum constant, include that
9460 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009461 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009462 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9463 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9464
Richard Smitha5370fb2017-12-08 22:57:11 +00009465 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009466 SmallString<64> PrettySourceValue;
9467 llvm::raw_svector_ostream OS(PrettySourceValue);
9468 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009469 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009470 else
9471 OS << Value;
9472
Richard Smitha5370fb2017-12-08 22:57:11 +00009473 // FIXME: We use a somewhat different formatting for the in-range cases and
9474 // cases involving boolean values for historical reasons. We should pick a
9475 // consistent way of presenting these diagnostics.
9476 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9477 S.DiagRuntimeBehavior(
9478 E->getOperatorLoc(), E,
9479 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9480 : diag::warn_tautological_bool_compare)
9481 << OS.str() << classifyConstantValue(Constant)
9482 << OtherT << OtherIsBooleanDespiteType << *Result
9483 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9484 } else {
9485 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9486 ? (HasEnumType(OriginalOther)
9487 ? diag::warn_unsigned_enum_always_true_comparison
9488 : diag::warn_unsigned_always_true_comparison)
9489 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009490
Richard Smitha5370fb2017-12-08 22:57:11 +00009491 S.Diag(E->getOperatorLoc(), Diag)
9492 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9493 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9494 }
9495
9496 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009497}
9498
John McCallcc7e5bf2010-05-06 08:58:33 +00009499/// Analyze the operands of the given comparison. Implements the
9500/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009501static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009502 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9503 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009504}
John McCall263a48b2010-01-04 23:31:57 +00009505
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009506/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009507///
Richard Trieu82402a02011-09-15 21:56:47 +00009508/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009509static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009510 // The type the comparison is being performed in.
9511 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009512
9513 // Only analyze comparison operators where both sides have been converted to
9514 // the same type.
9515 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9516 return AnalyzeImpConvsInComparison(S, E);
9517
9518 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009519 if (E->isValueDependent())
9520 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009521
Roman Lebedev6de129e2017-10-15 20:13:17 +00009522 Expr *LHS = E->getLHS();
9523 Expr *RHS = E->getRHS();
9524
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009525 if (T->isIntegralType(S.Context)) {
9526 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009527 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009528
Roman Lebedev6de129e2017-10-15 20:13:17 +00009529 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9530 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009531
Roman Lebedev6de129e2017-10-15 20:13:17 +00009532 // We don't care about expressions whose result is a constant.
9533 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9534 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009535
Roman Lebedev6de129e2017-10-15 20:13:17 +00009536 // We only care about expressions where just one side is literal
9537 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9538 // Is the constant on the RHS or LHS?
9539 const bool RhsConstant = IsRHSIntegralLiteral;
9540 Expr *Const = RhsConstant ? RHS : LHS;
9541 Expr *Other = RhsConstant ? LHS : RHS;
9542 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9543
9544 // Check whether an integer constant comparison results in a value
9545 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009546 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9547 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009548 }
9549 }
9550
9551 if (!T->hasUnsignedIntegerRepresentation()) {
9552 // We don't do anything special if this isn't an unsigned integral
9553 // comparison: we're only interested in integral comparisons, and
9554 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009555 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009556 }
9557
9558 LHS = LHS->IgnoreParenImpCasts();
9559 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009560
Alex Lorenzb57409f2018-02-07 20:45:39 +00009561 if (!S.getLangOpts().CPlusPlus) {
9562 // Avoid warning about comparison of integers with different signs when
9563 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9564 // the type of `E`.
9565 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9566 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9567 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9568 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9569 }
9570
John McCallcc7e5bf2010-05-06 08:58:33 +00009571 // Check to see if one of the (unmodified) operands is of different
9572 // signedness.
9573 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009574 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9575 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009576 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009577 signedOperand = LHS;
9578 unsignedOperand = RHS;
9579 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9580 signedOperand = RHS;
9581 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009582 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009583 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009584 }
9585
John McCallcc7e5bf2010-05-06 08:58:33 +00009586 // Otherwise, calculate the effective range of the signed operand.
9587 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009588
John McCallcc7e5bf2010-05-06 08:58:33 +00009589 // Go ahead and analyze implicit conversions in the operands. Note
9590 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009591 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9592 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009593
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009594 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009595 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009596 return;
John McCallca01b222010-01-04 23:21:16 +00009597
9598 // For (in)equality comparisons, if the unsigned operand is a
9599 // constant which cannot collide with a overflowed signed operand,
9600 // then reinterpreting the signed operand as unsigned will not
9601 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009602 if (E->isEqualityOp()) {
9603 unsigned comparisonWidth = S.Context.getIntWidth(T);
9604 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009605
John McCallcc7e5bf2010-05-06 08:58:33 +00009606 // We should never be unable to prove that the unsigned operand is
9607 // non-negative.
9608 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9609
9610 if (unsignedRange.Width < comparisonWidth)
9611 return;
9612 }
9613
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009614 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9615 S.PDiag(diag::warn_mixed_sign_comparison)
9616 << LHS->getType() << RHS->getType()
9617 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009618}
9619
John McCall1f425642010-11-11 03:21:53 +00009620/// Analyzes an attempt to assign the given value to a bitfield.
9621///
9622/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009623static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9624 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009625 assert(Bitfield->isBitField());
9626 if (Bitfield->isInvalidDecl())
9627 return false;
9628
John McCalldeebbcf2010-11-11 05:33:51 +00009629 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009630 QualType BitfieldType = Bitfield->getType();
9631 if (BitfieldType->isBooleanType())
9632 return false;
9633
9634 if (BitfieldType->isEnumeralType()) {
9635 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9636 // If the underlying enum type was not explicitly specified as an unsigned
9637 // type and the enum contain only positive values, MSVC++ will cause an
9638 // inconsistency by storing this as a signed type.
9639 if (S.getLangOpts().CPlusPlus11 &&
9640 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9641 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9642 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9643 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9644 << BitfieldEnumDecl->getNameAsString();
9645 }
9646 }
9647
John McCalldeebbcf2010-11-11 05:33:51 +00009648 if (Bitfield->getType()->isBooleanType())
9649 return false;
9650
Douglas Gregor789adec2011-02-04 13:09:01 +00009651 // Ignore value- or type-dependent expressions.
9652 if (Bitfield->getBitWidth()->isValueDependent() ||
9653 Bitfield->getBitWidth()->isTypeDependent() ||
9654 Init->isValueDependent() ||
9655 Init->isTypeDependent())
9656 return false;
9657
John McCall1f425642010-11-11 03:21:53 +00009658 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009659 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009660
Richard Smith5fab0c92011-12-28 19:48:30 +00009661 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009662 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9663 Expr::SE_AllowSideEffects)) {
9664 // The RHS is not constant. If the RHS has an enum type, make sure the
9665 // bitfield is wide enough to hold all the values of the enum without
9666 // truncation.
9667 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9668 EnumDecl *ED = EnumTy->getDecl();
9669 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9670
9671 // Enum types are implicitly signed on Windows, so check if there are any
9672 // negative enumerators to see if the enum was intended to be signed or
9673 // not.
9674 bool SignedEnum = ED->getNumNegativeBits() > 0;
9675
9676 // Check for surprising sign changes when assigning enum values to a
9677 // bitfield of different signedness. If the bitfield is signed and we
9678 // have exactly the right number of bits to store this unsigned enum,
9679 // suggest changing the enum to an unsigned type. This typically happens
9680 // on Windows where unfixed enums always use an underlying type of 'int'.
9681 unsigned DiagID = 0;
9682 if (SignedEnum && !SignedBitfield) {
9683 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9684 } else if (SignedBitfield && !SignedEnum &&
9685 ED->getNumPositiveBits() == FieldWidth) {
9686 DiagID = diag::warn_signed_bitfield_enum_conversion;
9687 }
9688
9689 if (DiagID) {
9690 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9691 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9692 SourceRange TypeRange =
9693 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9694 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9695 << SignedEnum << TypeRange;
9696 }
9697
9698 // Compute the required bitwidth. If the enum has negative values, we need
9699 // one more bit than the normal number of positive bits to represent the
9700 // sign bit.
9701 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9702 ED->getNumNegativeBits())
9703 : ED->getNumPositiveBits();
9704
9705 // Check the bitwidth.
9706 if (BitsNeeded > FieldWidth) {
9707 Expr *WidthExpr = Bitfield->getBitWidth();
9708 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9709 << Bitfield << ED;
9710 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9711 << BitsNeeded << ED << WidthExpr->getSourceRange();
9712 }
9713 }
9714
John McCall1f425642010-11-11 03:21:53 +00009715 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009716 }
John McCall1f425642010-11-11 03:21:53 +00009717
John McCall1f425642010-11-11 03:21:53 +00009718 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009719
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009720 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009721 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009722 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9723 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009724
John McCall1f425642010-11-11 03:21:53 +00009725 if (OriginalWidth <= FieldWidth)
9726 return false;
9727
Eli Friedmanc267a322012-01-26 23:11:39 +00009728 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009729 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009730 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009731
Eli Friedmanc267a322012-01-26 23:11:39 +00009732 // Check whether the stored value is equal to the original value.
9733 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009734 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009735 return false;
9736
Eli Friedmanc267a322012-01-26 23:11:39 +00009737 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009738 // therefore don't strictly fit into a signed bitfield of width 1.
9739 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009740 return false;
9741
John McCall1f425642010-11-11 03:21:53 +00009742 std::string PrettyValue = Value.toString(10);
9743 std::string PrettyTrunc = TruncatedValue.toString(10);
9744
9745 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9746 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9747 << Init->getSourceRange();
9748
9749 return true;
9750}
9751
John McCalld2a53122010-11-09 23:24:47 +00009752/// Analyze the given simple or compound assignment for warning-worthy
9753/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009754static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009755 // Just recurse on the LHS.
9756 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9757
9758 // We want to recurse on the RHS as normal unless we're assigning to
9759 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009760 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009761 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009762 E->getOperatorLoc())) {
9763 // Recurse, ignoring any implicit conversions on the RHS.
9764 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9765 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009766 }
9767 }
9768
9769 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9770}
9771
John McCall263a48b2010-01-04 23:31: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 SourceType, QualType T,
9774 SourceLocation CContext, unsigned diag,
9775 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009776 if (pruneControlFlow) {
9777 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9778 S.PDiag(diag)
9779 << SourceType << T << E->getSourceRange()
9780 << SourceRange(CContext));
9781 return;
9782 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009783 S.Diag(E->getExprLoc(), diag)
9784 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9785}
9786
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009787/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009788static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9789 SourceLocation CContext,
9790 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009791 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009792}
9793
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009794/// Analyze the given compound assignment for the possible losing of
9795/// floating-point precision.
9796static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9797 assert(isa<CompoundAssignOperator>(E) &&
9798 "Must be compound assignment operation");
9799 // Recurse on the LHS and RHS in here
9800 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9801 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9802
9803 // Now check the outermost expression
9804 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9805 const auto *RBT = cast<CompoundAssignOperator>(E)
9806 ->getComputationResultType()
9807 ->getAs<BuiltinType>();
9808
9809 // If both source and target are floating points.
9810 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9811 // Builtin FP kinds are ordered by increasing FP rank.
9812 if (ResultBT->getKind() < RBT->getKind())
9813 // We don't want to warn for system macro.
9814 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9815 // warn about dropping FP rank.
9816 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9817 E->getOperatorLoc(),
9818 diag::warn_impcast_float_result_precision);
9819}
Richard Trieube234c32016-04-21 21:04:55 +00009820
9821/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009822static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9823 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009824 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009825 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009826
9827 Expr *InnerE = E->IgnoreParenImpCasts();
9828 // We also want to warn on, e.g., "int i = -1.234"
9829 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9830 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9831 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9832
9833 const bool IsLiteral =
9834 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9835
9836 llvm::APFloat Value(0.0);
9837 bool IsConstant =
9838 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9839 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009840 return DiagnoseImpCast(S, E, T, CContext,
9841 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009842 }
9843
Chandler Carruth016ef402011-04-10 08:36:24 +00009844 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009845
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009846 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9847 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009848 llvm::APFloat::opStatus Result = Value.convertToInteger(
9849 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9850
9851 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009852 if (IsLiteral) return;
9853 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9854 PruneWarnings);
9855 }
9856
Erich Keanea4c48c62018-05-08 21:26:21 +00009857 // Conversion of a floating-point value to a non-bool integer where the
9858 // integral part cannot be represented by the integer type is undefined.
9859 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9860 return DiagnoseImpCast(
9861 S, E, T, CContext,
9862 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009863 : diag::warn_impcast_float_to_integer_out_of_range,
9864 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009865
Richard Trieube234c32016-04-21 21:04:55 +00009866 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009867 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009868 // Warn on floating point literal to integer.
9869 DiagID = diag::warn_impcast_literal_float_to_integer;
9870 } else if (IntegerValue == 0) {
9871 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9872 return DiagnoseImpCast(S, E, T, CContext,
9873 diag::warn_impcast_float_integer, PruneWarnings);
9874 }
9875 // Warn on non-zero to zero conversion.
9876 DiagID = diag::warn_impcast_float_to_integer_zero;
9877 } else {
9878 if (IntegerValue.isUnsigned()) {
9879 if (!IntegerValue.isMaxValue()) {
9880 return DiagnoseImpCast(S, E, T, CContext,
9881 diag::warn_impcast_float_integer, PruneWarnings);
9882 }
9883 } else { // IntegerValue.isSigned()
9884 if (!IntegerValue.isMaxSignedValue() &&
9885 !IntegerValue.isMinSignedValue()) {
9886 return DiagnoseImpCast(S, E, T, CContext,
9887 diag::warn_impcast_float_integer, PruneWarnings);
9888 }
9889 }
9890 // Warn on evaluatable floating point expression to integer conversion.
9891 DiagID = diag::warn_impcast_float_to_integer;
9892 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009893
Eli Friedman07185912013-08-29 23:44:43 +00009894 // FIXME: Force the precision of the source value down so we don't print
9895 // digits which are usually useless (we don't really care here if we
9896 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9897 // would automatically print the shortest representation, but it's a bit
9898 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009899 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009900 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9901 precision = (precision * 59 + 195) / 196;
9902 Value.toString(PrettySourceValue, precision);
9903
David Blaikie9b88cc02012-05-15 17:18:27 +00009904 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009905 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009906 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009907 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009908 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009909
Richard Trieube234c32016-04-21 21:04:55 +00009910 if (PruneWarnings) {
9911 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9912 S.PDiag(DiagID)
9913 << E->getType() << T.getUnqualifiedType()
9914 << PrettySourceValue << PrettyTargetValue
9915 << E->getSourceRange() << SourceRange(CContext));
9916 } else {
9917 S.Diag(E->getExprLoc(), DiagID)
9918 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9919 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9920 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009921}
9922
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009923static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9924 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009925 if (!Range.Width) return "0";
9926
9927 llvm::APSInt ValueInRange = Value;
9928 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009929 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009930 return ValueInRange.toString(10);
9931}
9932
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009933static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009934 if (!isa<ImplicitCastExpr>(Ex))
9935 return false;
9936
9937 Expr *InnerE = Ex->IgnoreParenImpCasts();
9938 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9939 const Type *Source =
9940 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9941 if (Target->isDependentType())
9942 return false;
9943
9944 const BuiltinType *FloatCandidateBT =
9945 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9946 const Type *BoolCandidateType = ToBool ? Target : Source;
9947
9948 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9949 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9950}
9951
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009952static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9953 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009954 unsigned NumArgs = TheCall->getNumArgs();
9955 for (unsigned i = 0; i < NumArgs; ++i) {
9956 Expr *CurrA = TheCall->getArg(i);
9957 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9958 continue;
9959
9960 bool IsSwapped = ((i > 0) &&
9961 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9962 IsSwapped |= ((i < (NumArgs - 1)) &&
9963 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9964 if (IsSwapped) {
9965 // Warn on this floating-point to bool conversion.
9966 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9967 CurrA->getType(), CC,
9968 diag::warn_impcast_floating_point_to_bool);
9969 }
9970 }
9971}
9972
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009973static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9974 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009975 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9976 E->getExprLoc()))
9977 return;
9978
Richard Trieu09d6b802016-01-08 23:35:06 +00009979 // Don't warn on functions which have return type nullptr_t.
9980 if (isa<CallExpr>(E))
9981 return;
9982
Richard Trieu5b993502014-10-15 03:42:06 +00009983 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9984 const Expr::NullPointerConstantKind NullKind =
9985 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9986 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9987 return;
9988
9989 // Return if target type is a safe conversion.
9990 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9991 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9992 return;
9993
9994 SourceLocation Loc = E->getSourceRange().getBegin();
9995
Richard Trieu0a5e1662016-02-13 00:58:53 +00009996 // Venture through the macro stacks to get to the source of macro arguments.
9997 // The new location is a better location than the complete location that was
9998 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009999 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10000 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +000010001
Richard Trieu5b993502014-10-15 03:42:06 +000010002 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +000010003 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10004 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10005 Loc, S.SourceMgr, S.getLangOpts());
10006 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +000010007 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +000010008 }
10009
10010 // Only warn if the null and context location are in the same macro expansion.
10011 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10012 return;
10013
10014 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010015 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000010016 << FixItHint::CreateReplacement(Loc,
10017 S.getFixItZeroLiteralForType(T, Loc));
10018}
10019
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010020static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10021 ObjCArrayLiteral *ArrayLiteral);
10022
10023static void
10024checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10025 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000010026
10027/// Check a single element within a collection literal against the
10028/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010029static void checkObjCCollectionLiteralElement(Sema &S,
10030 QualType TargetElementType,
10031 Expr *Element,
10032 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010033 // Skip a bitcast to 'id' or qualified 'id'.
10034 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10035 if (ICE->getCastKind() == CK_BitCast &&
10036 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10037 Element = ICE->getSubExpr();
10038 }
10039
10040 QualType ElementType = Element->getType();
10041 ExprResult ElementResult(Element);
10042 if (ElementType->getAs<ObjCObjectPointerType>() &&
10043 S.CheckSingleAssignmentConstraints(TargetElementType,
10044 ElementResult,
10045 false, false)
10046 != Sema::Compatible) {
10047 S.Diag(Element->getLocStart(),
10048 diag::warn_objc_collection_literal_element)
10049 << ElementType << ElementKind << TargetElementType
10050 << Element->getSourceRange();
10051 }
10052
10053 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10054 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10055 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10056 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10057}
10058
10059/// Check an Objective-C array literal being converted to the given
10060/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010061static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10062 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010063 if (!S.NSArrayDecl)
10064 return;
10065
10066 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10067 if (!TargetObjCPtr)
10068 return;
10069
10070 if (TargetObjCPtr->isUnspecialized() ||
10071 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10072 != S.NSArrayDecl->getCanonicalDecl())
10073 return;
10074
10075 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10076 if (TypeArgs.size() != 1)
10077 return;
10078
10079 QualType TargetElementType = TypeArgs[0];
10080 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10081 checkObjCCollectionLiteralElement(S, TargetElementType,
10082 ArrayLiteral->getElement(I),
10083 0);
10084 }
10085}
10086
10087/// Check an Objective-C dictionary literal being converted to the given
10088/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010089static void
10090checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10091 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010092 if (!S.NSDictionaryDecl)
10093 return;
10094
10095 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10096 if (!TargetObjCPtr)
10097 return;
10098
10099 if (TargetObjCPtr->isUnspecialized() ||
10100 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10101 != S.NSDictionaryDecl->getCanonicalDecl())
10102 return;
10103
10104 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10105 if (TypeArgs.size() != 2)
10106 return;
10107
10108 QualType TargetKeyType = TypeArgs[0];
10109 QualType TargetObjectType = TypeArgs[1];
10110 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10111 auto Element = DictionaryLiteral->getKeyValueElement(I);
10112 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10113 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10114 }
10115}
10116
Richard Trieufc404c72016-02-05 23:02:38 +000010117// Helper function to filter out cases for constant width constant conversion.
10118// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010119static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10120 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010121 // If initializing from a constant, and the constant starts with '0',
10122 // then it is a binary, octal, or hexadecimal. Allow these constants
10123 // to fill all the bits, even if there is a sign change.
10124 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10125 const char FirstLiteralCharacter =
10126 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10127 if (FirstLiteralCharacter == '0')
10128 return false;
10129 }
10130
10131 // If the CC location points to a '{', and the type is char, then assume
10132 // assume it is an array initialization.
10133 if (CC.isValid() && T->isCharType()) {
10134 const char FirstContextCharacter =
10135 S.getSourceManager().getCharacterData(CC)[0];
10136 if (FirstContextCharacter == '{')
10137 return false;
10138 }
10139
10140 return true;
10141}
10142
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010143static void
10144CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10145 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010146 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010147
John McCallcc7e5bf2010-05-06 08:58:33 +000010148 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10149 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10150 if (Source == Target) return;
10151 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010152
Chandler Carruthc22845a2011-07-26 05:40:03 +000010153 // If the conversion context location is invalid don't complain. We also
10154 // don't want to emit a warning if the issue occurs from the expansion of
10155 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10156 // delay this check as long as possible. Once we detect we are in that
10157 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010158 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010159 return;
10160
Richard Trieu021baa32011-09-23 20:10:00 +000010161 // Diagnose implicit casts to bool.
10162 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10163 if (isa<StringLiteral>(E))
10164 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010165 // and expressions, for instance, assert(0 && "error here"), are
10166 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010167 return DiagnoseImpCast(S, E, T, CC,
10168 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010169 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10170 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10171 // This covers the literal expressions that evaluate to Objective-C
10172 // objects.
10173 return DiagnoseImpCast(S, E, T, CC,
10174 diag::warn_impcast_objective_c_literal_to_bool);
10175 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010176 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10177 // Warn on pointer to bool conversion that is always true.
10178 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10179 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010180 }
Richard Trieu021baa32011-09-23 20:10:00 +000010181 }
John McCall263a48b2010-01-04 23:31:57 +000010182
Douglas Gregor5054cb02015-07-07 03:58:22 +000010183 // Check implicit casts from Objective-C collection literals to specialized
10184 // collection types, e.g., NSArray<NSString *> *.
10185 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10186 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10187 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10188 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10189
John McCall263a48b2010-01-04 23:31:57 +000010190 // Strip vector types.
10191 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010192 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010193 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010194 return;
John McCallacf0ee52010-10-08 02:01:28 +000010195 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010196 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010197
Chris Lattneree7286f2011-06-14 04:51:15 +000010198 // If the vector cast is cast between two vectors of the same size, it is
10199 // a bitcast, not a conversion.
10200 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10201 return;
John McCall263a48b2010-01-04 23:31:57 +000010202
10203 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10204 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10205 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010206 if (auto VecTy = dyn_cast<VectorType>(Target))
10207 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010208
10209 // Strip complex types.
10210 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010211 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010212 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010213 return;
10214
Tim Northover02416372017-08-08 23:18:05 +000010215 return DiagnoseImpCast(S, E, T, CC,
10216 S.getLangOpts().CPlusPlus
10217 ? diag::err_impcast_complex_scalar
10218 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010219 }
John McCall263a48b2010-01-04 23:31:57 +000010220
10221 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10222 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10223 }
10224
10225 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10226 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10227
10228 // If the source is floating point...
10229 if (SourceBT && SourceBT->isFloatingPoint()) {
10230 // ...and the target is floating point...
10231 if (TargetBT && TargetBT->isFloatingPoint()) {
10232 // ...then warn if we're dropping FP rank.
10233
10234 // Builtin FP kinds are ordered by increasing FP rank.
10235 if (SourceBT->getKind() > TargetBT->getKind()) {
10236 // Don't warn about float constants that are precisely
10237 // representable in the target type.
10238 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010239 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010240 // Value might be a float, a float vector, or a float complex.
10241 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010242 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10243 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010244 return;
10245 }
10246
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010247 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010248 return;
10249
John McCallacf0ee52010-10-08 02:01:28 +000010250 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010251 }
10252 // ... or possibly if we're increasing rank, too
10253 else if (TargetBT->getKind() > SourceBT->getKind()) {
10254 if (S.SourceMgr.isInSystemMacro(CC))
10255 return;
10256
10257 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010258 }
10259 return;
10260 }
10261
Richard Trieube234c32016-04-21 21:04:55 +000010262 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010263 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010264 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010265 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010266
Richard Trieube234c32016-04-21 21:04:55 +000010267 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010268 }
John McCall263a48b2010-01-04 23:31:57 +000010269
Richard Smith54894fd2015-12-30 01:06:52 +000010270 // Detect the case where a call result is converted from floating-point to
10271 // to bool, and the final argument to the call is converted from bool, to
10272 // discover this typo:
10273 //
10274 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10275 //
10276 // FIXME: This is an incredibly special case; is there some more general
10277 // way to detect this class of misplaced-parentheses bug?
10278 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010279 // Check last argument of function call to see if it is an
10280 // implicit cast from a type matching the type the result
10281 // is being cast to.
10282 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010283 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010284 Expr *LastA = CEx->getArg(NumArgs - 1);
10285 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010286 if (isa<ImplicitCastExpr>(LastA) &&
10287 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010288 // Warn on this floating-point to bool conversion
10289 DiagnoseImpCast(S, E, T, CC,
10290 diag::warn_impcast_floating_point_to_bool);
10291 }
10292 }
10293 }
John McCall263a48b2010-01-04 23:31:57 +000010294 return;
10295 }
10296
Richard Trieu5b993502014-10-15 03:42:06 +000010297 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010298
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010299 S.DiscardMisalignedMemberAddress(Target, E);
10300
David Blaikie9366d2b2012-06-19 21:19:06 +000010301 if (!Source->isIntegerType() || !Target->isIntegerType())
10302 return;
10303
David Blaikie7555b6a2012-05-15 16:56:36 +000010304 // TODO: remove this early return once the false positives for constant->bool
10305 // in templates, macros, etc, are reduced or removed.
10306 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10307 return;
10308
John McCallcc7e5bf2010-05-06 08:58:33 +000010309 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010310 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010311
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010312 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010313 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010314 // TODO: this should happen for bitfield stores, too.
10315 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010316 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010317 if (S.SourceMgr.isInSystemMacro(CC))
10318 return;
10319
John McCall18a2c2c2010-11-09 22:22:12 +000010320 std::string PrettySourceValue = Value.toString(10);
10321 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010322
Ted Kremenek33ba9952011-10-22 02:37:33 +000010323 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10324 S.PDiag(diag::warn_impcast_integer_precision_constant)
10325 << PrettySourceValue << PrettyTargetValue
10326 << E->getType() << T << E->getSourceRange()
10327 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010328 return;
10329 }
10330
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010331 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10332 if (S.SourceMgr.isInSystemMacro(CC))
10333 return;
10334
David Blaikie9455da02012-04-12 22:40:54 +000010335 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010336 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10337 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010338 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010339 }
10340
Richard Trieudcb55572016-01-29 23:51:16 +000010341 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10342 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10343 // Warn when doing a signed to signed conversion, warn if the positive
10344 // source value is exactly the width of the target type, which will
10345 // cause a negative value to be stored.
10346
10347 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010348 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10349 !S.SourceMgr.isInSystemMacro(CC)) {
10350 if (isSameWidthConstantConversion(S, E, T, CC)) {
10351 std::string PrettySourceValue = Value.toString(10);
10352 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010353
Richard Trieufc404c72016-02-05 23:02:38 +000010354 S.DiagRuntimeBehavior(
10355 E->getExprLoc(), E,
10356 S.PDiag(diag::warn_impcast_integer_precision_constant)
10357 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10358 << E->getSourceRange() << clang::SourceRange(CC));
10359 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010360 }
10361 }
Richard Trieufc404c72016-02-05 23:02:38 +000010362
Richard Trieudcb55572016-01-29 23:51:16 +000010363 // Fall through for non-constants to give a sign conversion warning.
10364 }
10365
John McCallcc7e5bf2010-05-06 08:58:33 +000010366 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10367 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10368 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010369 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010370 return;
10371
John McCallcc7e5bf2010-05-06 08:58:33 +000010372 unsigned DiagID = diag::warn_impcast_integer_sign;
10373
10374 // Traditionally, gcc has warned about this under -Wsign-compare.
10375 // We also want to warn about it in -Wconversion.
10376 // So if -Wconversion is off, use a completely identical diagnostic
10377 // in the sign-compare group.
10378 // The conditional-checking code will
10379 if (ICContext) {
10380 DiagID = diag::warn_impcast_integer_sign_conditional;
10381 *ICContext = true;
10382 }
10383
John McCallacf0ee52010-10-08 02:01:28 +000010384 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010385 }
10386
Douglas Gregora78f1932011-02-22 02:45:07 +000010387 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010388 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10389 // type, to give us better diagnostics.
10390 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010391 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010392 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10393 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10394 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10395 SourceType = S.Context.getTypeDeclType(Enum);
10396 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10397 }
10398 }
10399
Douglas Gregora78f1932011-02-22 02:45:07 +000010400 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10401 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010402 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10403 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010404 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010405 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010406 return;
10407
Douglas Gregor364f7db2011-03-12 00:14:31 +000010408 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010409 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010410 }
John McCall263a48b2010-01-04 23:31:57 +000010411}
10412
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010413static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10414 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010415
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010416static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10417 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010418 E = E->IgnoreParenImpCasts();
10419
10420 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010421 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010422
John McCallacf0ee52010-10-08 02:01:28 +000010423 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010424 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010425 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010426}
10427
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010428static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10429 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010430 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010431
10432 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010433 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10434 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010435
10436 // If -Wconversion would have warned about either of the candidates
10437 // for a signedness conversion to the context type...
10438 if (!Suspicious) return;
10439
10440 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010441 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010442 return;
10443
John McCallcc7e5bf2010-05-06 08:58:33 +000010444 // ...then check whether it would have warned about either of the
10445 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010446 if (E->getType() == T) return;
10447
10448 Suspicious = false;
10449 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10450 E->getType(), CC, &Suspicious);
10451 if (!Suspicious)
10452 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010453 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010454}
10455
Richard Trieu65724892014-11-15 06:37:39 +000010456/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10457/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010458static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010459 if (S.getLangOpts().Bool)
10460 return;
10461 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10462}
10463
John McCallcc7e5bf2010-05-06 08:58:33 +000010464/// AnalyzeImplicitConversions - Find and report any interesting
10465/// implicit conversions in the given expression. There are a couple
10466/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010467static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10468 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010469 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010470 Expr *E = OrigE->IgnoreParenImpCasts();
10471
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010472 if (E->isTypeDependent() || E->isValueDependent())
10473 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010474
John McCallcc7e5bf2010-05-06 08:58:33 +000010475 // For conditional operators, we analyze the arguments as if they
10476 // were being fed directly into the output.
10477 if (isa<ConditionalOperator>(E)) {
10478 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010479 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010480 return;
10481 }
10482
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010483 // Check implicit argument conversions for function calls.
10484 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10485 CheckImplicitArgumentConversions(S, Call, CC);
10486
John McCallcc7e5bf2010-05-06 08:58:33 +000010487 // Go ahead and check any implicit conversions we might have skipped.
10488 // The non-canonical typecheck is just an optimization;
10489 // CheckImplicitConversion will filter out dead implicit conversions.
10490 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010491 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010492
10493 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010494
10495 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10496 // The bound subexpressions in a PseudoObjectExpr are not reachable
10497 // as transitive children.
10498 // FIXME: Use a more uniform representation for this.
10499 for (auto *SE : POE->semantics())
10500 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10501 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010502 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010503
John McCallcc7e5bf2010-05-06 08:58:33 +000010504 // Skip past explicit casts.
10505 if (isa<ExplicitCastExpr>(E)) {
10506 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010507 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010508 }
10509
John McCalld2a53122010-11-09 23:24:47 +000010510 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10511 // Do a somewhat different check with comparison operators.
10512 if (BO->isComparisonOp())
10513 return AnalyzeComparison(S, BO);
10514
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010515 // And with simple assignments.
10516 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010517 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010518 // And with compound assignments.
10519 if (BO->isAssignmentOp())
10520 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010521 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010522
10523 // These break the otherwise-useful invariant below. Fortunately,
10524 // we don't really need to recurse into them, because any internal
10525 // expressions should have been analyzed already when they were
10526 // built into statements.
10527 if (isa<StmtExpr>(E)) return;
10528
10529 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010530 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010531
10532 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010533 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010534 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010535 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010536 for (Stmt *SubStmt : E->children()) {
10537 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010538 if (!ChildExpr)
10539 continue;
10540
Richard Trieu955231d2014-01-25 01:10:35 +000010541 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010542 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010543 // Ignore checking string literals that are in logical and operators.
10544 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010545 continue;
10546 AnalyzeImplicitConversions(S, ChildExpr, CC);
10547 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010548
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010549 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010550 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10551 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010552 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010553
10554 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10555 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010556 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010557 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010558
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010559 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10560 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010561 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010562}
10563
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010564/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010565static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10566 // Taking into account implicit conversions,
10567 // allow any integer.
10568 if (!E->getType()->isIntegerType()) {
10569 S.Diag(E->getLocStart(),
10570 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10571 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010572 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010573 // Potentially emit standard warnings for implicit conversions if enabled
10574 // using -Wconversion.
10575 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10576 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010577}
10578
Richard Trieuc1888e02014-06-28 23:25:37 +000010579// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10580// Returns true when emitting a warning about taking the address of a reference.
10581static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010582 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010583 E = E->IgnoreParenImpCasts();
10584
10585 const FunctionDecl *FD = nullptr;
10586
10587 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10588 if (!DRE->getDecl()->getType()->isReferenceType())
10589 return false;
10590 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10591 if (!M->getMemberDecl()->getType()->isReferenceType())
10592 return false;
10593 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010594 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010595 return false;
10596 FD = Call->getDirectCallee();
10597 } else {
10598 return false;
10599 }
10600
10601 SemaRef.Diag(E->getExprLoc(), PD);
10602
10603 // If possible, point to location of function.
10604 if (FD) {
10605 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10606 }
10607
10608 return true;
10609}
10610
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010611// Returns true if the SourceLocation is expanded from any macro body.
10612// Returns false if the SourceLocation is invalid, is from not in a macro
10613// expansion, or is from expanded from a top-level macro argument.
10614static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10615 if (Loc.isInvalid())
10616 return false;
10617
10618 while (Loc.isMacroID()) {
10619 if (SM.isMacroBodyExpansion(Loc))
10620 return true;
10621 Loc = SM.getImmediateMacroCallerLoc(Loc);
10622 }
10623
10624 return false;
10625}
10626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010627/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010628/// \param E the expression containing the pointer
10629/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10630/// compared to a null pointer
10631/// \param IsEqual True when the comparison is equal to a null pointer
10632/// \param Range Extra SourceRange to highlight in the diagnostic
10633void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10634 Expr::NullPointerConstantKind NullKind,
10635 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010636 if (!E)
10637 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010638
10639 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010640 if (E->getExprLoc().isMacroID()) {
10641 const SourceManager &SM = getSourceManager();
10642 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10643 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010644 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010645 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010646 E = E->IgnoreImpCasts();
10647
10648 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10649
Richard Trieuf7432752014-06-06 21:39:26 +000010650 if (isa<CXXThisExpr>(E)) {
10651 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10652 : diag::warn_this_bool_conversion;
10653 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10654 return;
10655 }
10656
Richard Trieu3bb8b562014-02-26 02:36:06 +000010657 bool IsAddressOf = false;
10658
10659 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10660 if (UO->getOpcode() != UO_AddrOf)
10661 return;
10662 IsAddressOf = true;
10663 E = UO->getSubExpr();
10664 }
10665
Richard Trieuc1888e02014-06-28 23:25:37 +000010666 if (IsAddressOf) {
10667 unsigned DiagID = IsCompare
10668 ? diag::warn_address_of_reference_null_compare
10669 : diag::warn_address_of_reference_bool_conversion;
10670 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10671 << IsEqual;
10672 if (CheckForReference(*this, E, PD)) {
10673 return;
10674 }
10675 }
10676
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010677 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10678 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010679 std::string Str;
10680 llvm::raw_string_ostream S(Str);
10681 E->printPretty(S, nullptr, getPrintingPolicy());
10682 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10683 : diag::warn_cast_nonnull_to_bool;
10684 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10685 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010686 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010687 };
10688
10689 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10690 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10691 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010692 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10693 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010694 return;
10695 }
10696 }
10697 }
10698
Richard Trieu3bb8b562014-02-26 02:36:06 +000010699 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010700 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010701 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10702 D = R->getDecl();
10703 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10704 D = M->getMemberDecl();
10705 }
10706
10707 // Weak Decls can be null.
10708 if (!D || D->isWeak())
10709 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010710
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010711 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010712 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10713 if (getCurFunction() &&
10714 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010715 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10716 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010717 return;
10718 }
10719
10720 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010721 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010722 assert(ParamIter != FD->param_end());
10723 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10724
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010725 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10726 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010727 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010728 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010729 }
George Burgess IV850269a2015-12-08 22:02:00 +000010730
Joel E. Denny81508102018-03-13 14:51:22 +000010731 for (const ParamIdx &ArgNo : NonNull->args()) {
10732 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010733 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010734 return;
10735 }
George Burgess IV850269a2015-12-08 22:02:00 +000010736 }
10737 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010738 }
10739 }
George Burgess IV850269a2015-12-08 22:02:00 +000010740 }
10741
Richard Trieu3bb8b562014-02-26 02:36:06 +000010742 QualType T = D->getType();
10743 const bool IsArray = T->isArrayType();
10744 const bool IsFunction = T->isFunctionType();
10745
Richard Trieuc1888e02014-06-28 23:25:37 +000010746 // Address of function is used to silence the function warning.
10747 if (IsAddressOf && IsFunction) {
10748 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010749 }
10750
10751 // Found nothing.
10752 if (!IsAddressOf && !IsFunction && !IsArray)
10753 return;
10754
10755 // Pretty print the expression for the diagnostic.
10756 std::string Str;
10757 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010758 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010759
10760 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10761 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010762 enum {
10763 AddressOf,
10764 FunctionPointer,
10765 ArrayPointer
10766 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010767 if (IsAddressOf)
10768 DiagType = AddressOf;
10769 else if (IsFunction)
10770 DiagType = FunctionPointer;
10771 else if (IsArray)
10772 DiagType = ArrayPointer;
10773 else
10774 llvm_unreachable("Could not determine diagnostic.");
10775 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10776 << Range << IsEqual;
10777
10778 if (!IsFunction)
10779 return;
10780
10781 // Suggest '&' to silence the function warning.
10782 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10783 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10784
10785 // Check to see if '()' fixit should be emitted.
10786 QualType ReturnType;
10787 UnresolvedSet<4> NonTemplateOverloads;
10788 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10789 if (ReturnType.isNull())
10790 return;
10791
10792 if (IsCompare) {
10793 // There are two cases here. If there is null constant, the only suggest
10794 // for a pointer return type. If the null is 0, then suggest if the return
10795 // type is a pointer or an integer type.
10796 if (!ReturnType->isPointerType()) {
10797 if (NullKind == Expr::NPCK_ZeroExpression ||
10798 NullKind == Expr::NPCK_ZeroLiteral) {
10799 if (!ReturnType->isIntegerType())
10800 return;
10801 } else {
10802 return;
10803 }
10804 }
10805 } else { // !IsCompare
10806 // For function to bool, only suggest if the function pointer has bool
10807 // return type.
10808 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10809 return;
10810 }
10811 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010812 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010813}
10814
John McCallcc7e5bf2010-05-06 08:58:33 +000010815/// Diagnoses "dangerous" implicit conversions within the given
10816/// expression (which is a full expression). Implements -Wconversion
10817/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010818///
10819/// \param CC the "context" location of the implicit conversion, i.e.
10820/// the most location of the syntactic entity requiring the implicit
10821/// conversion
10822void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010823 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010824 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010825 return;
10826
10827 // Don't diagnose for value- or type-dependent expressions.
10828 if (E->isTypeDependent() || E->isValueDependent())
10829 return;
10830
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010831 // Check for array bounds violations in cases where the check isn't triggered
10832 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10833 // ArraySubscriptExpr is on the RHS of a variable initialization.
10834 CheckArrayAccess(E);
10835
John McCallacf0ee52010-10-08 02:01:28 +000010836 // This is not the right CC for (e.g.) a variable initialization.
10837 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010838}
10839
Richard Trieu65724892014-11-15 06:37:39 +000010840/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10841/// Input argument E is a logical expression.
10842void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10843 ::CheckBoolLikeConversion(*this, E, CC);
10844}
10845
Richard Smith9f7df0c2017-06-26 23:19:32 +000010846/// Diagnose when expression is an integer constant expression and its evaluation
10847/// results in integer overflow
10848void Sema::CheckForIntOverflow (Expr *E) {
10849 // Use a work list to deal with nested struct initializers.
10850 SmallVector<Expr *, 2> Exprs(1, E);
10851
10852 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010853 Expr *OriginalE = Exprs.pop_back_val();
10854 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010855
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010856 if (isa<BinaryOperator>(E)) {
10857 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010858 continue;
10859 }
10860
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010861 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010862 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010863 else if (isa<ObjCBoxedExpr>(OriginalE))
10864 E->EvaluateForOverflow(Context);
10865 else if (auto Call = dyn_cast<CallExpr>(E))
10866 Exprs.append(Call->arg_begin(), Call->arg_end());
10867 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10868 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010869 } while (!Exprs.empty());
10870}
10871
Richard Smithc406cb72013-01-17 01:17:56 +000010872namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010873
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010874/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010875/// same object.
10876class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010877 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010878
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010879 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010880 /// unsequenced if one is an ancestor or a descendent of the other. When we
10881 /// finish processing an expression with sequencing, such as a comma
10882 /// expression, we fold its tree nodes into its parent, since they are
10883 /// unsequenced with respect to nodes we will visit later.
10884 class SequenceTree {
10885 struct Value {
10886 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10887 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010888 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010889 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010890 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010891
10892 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010893 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010894 /// to some other region.
10895 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010896 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010897
10898 unsigned Index = 0;
10899
10900 explicit Seq(unsigned N) : Index(N) {}
10901
Richard Smithc406cb72013-01-17 01:17:56 +000010902 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010903 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010904 };
10905
10906 SequenceTree() { Values.push_back(Value(0)); }
10907 Seq root() const { return Seq(0); }
10908
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010909 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010910 /// subset of \p Parent. This sequence of operations is sequenced with
10911 /// respect to other children of \p Parent.
10912 Seq allocate(Seq Parent) {
10913 Values.push_back(Value(Parent.Index));
10914 return Seq(Values.size() - 1);
10915 }
10916
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010917 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010918 void merge(Seq S) {
10919 Values[S.Index].Merged = true;
10920 }
10921
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010922 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010923 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10924 /// should have been merged into its parent as appropriate.
10925 bool isUnsequenced(Seq Cur, Seq Old) {
10926 unsigned C = representative(Cur.Index);
10927 unsigned Target = representative(Old.Index);
10928 while (C >= Target) {
10929 if (C == Target)
10930 return true;
10931 C = Values[C].Parent;
10932 }
10933 return false;
10934 }
10935
10936 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010937 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010938 unsigned representative(unsigned K) {
10939 if (Values[K].Merged)
10940 // Perform path compression as we go.
10941 return Values[K].Parent = representative(Values[K].Parent);
10942 return K;
10943 }
10944 };
10945
10946 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010947 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010948
10949 /// Different flavors of object usage which we track. We only track the
10950 /// least-sequenced usage of each kind.
10951 enum UsageKind {
10952 /// A read of an object. Multiple unsequenced reads are OK.
10953 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010954
Richard Smithc406cb72013-01-17 01:17:56 +000010955 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010956 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010957 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010958
Richard Smithc406cb72013-01-17 01:17:56 +000010959 /// A modification of an object which is not sequenced before the value
10960 /// computation of the expression, such as n++.
10961 UK_ModAsSideEffect,
10962
10963 UK_Count = UK_ModAsSideEffect + 1
10964 };
10965
10966 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010967 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010968 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010969
10970 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010971 };
10972
10973 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010974 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010975
Richard Smithc406cb72013-01-17 01:17:56 +000010976 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010977 bool Diagnosed = false;
10978
10979 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010980 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010981 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010982
10983 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010984
Richard Smithc406cb72013-01-17 01:17:56 +000010985 /// Sequenced regions within the expression.
10986 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010987
Richard Smithc406cb72013-01-17 01:17:56 +000010988 /// Declaration modifications and references which we have seen.
10989 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010990
Richard Smithc406cb72013-01-17 01:17:56 +000010991 /// The region we are currently within.
10992 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010993
Richard Smithc406cb72013-01-17 01:17:56 +000010994 /// Filled in with declarations which were modified as a side-effect
10995 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010996 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10997
Richard Smithd33f5202013-01-17 23:18:09 +000010998 /// Expressions to check later. We defer checking these to reduce
10999 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011000 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000011001
11002 /// RAII object wrapping the visitation of a sequenced subexpression of an
11003 /// expression. At the end of this process, the side-effects of the evaluation
11004 /// become sequenced with respect to the value computation of the result, so
11005 /// we downgrade any UK_ModAsSideEffect within the evaluation to
11006 /// UK_ModAsValue.
11007 struct SequencedSubexpression {
11008 SequencedSubexpression(SequenceChecker &Self)
11009 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11010 Self.ModAsSideEffect = &ModAsSideEffect;
11011 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011012
Richard Smithc406cb72013-01-17 01:17:56 +000011013 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000011014 for (auto &M : llvm::reverse(ModAsSideEffect)) {
11015 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000011016 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000011017 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11018 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000011019 }
11020 Self.ModAsSideEffect = OldModAsSideEffect;
11021 }
11022
11023 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011024 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011025 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000011026 };
11027
Richard Smith40238f02013-06-20 22:21:56 +000011028 /// RAII object wrapping the visitation of a subexpression which we might
11029 /// choose to evaluate as a constant. If any subexpression is evaluated and
11030 /// found to be non-constant, this allows us to suppress the evaluation of
11031 /// the outer expression.
11032 class EvaluationTracker {
11033 public:
11034 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011035 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000011036 Self.EvalTracker = this;
11037 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011038
Richard Smith40238f02013-06-20 22:21:56 +000011039 ~EvaluationTracker() {
11040 Self.EvalTracker = Prev;
11041 if (Prev)
11042 Prev->EvalOK &= EvalOK;
11043 }
11044
11045 bool evaluate(const Expr *E, bool &Result) {
11046 if (!EvalOK || E->isValueDependent())
11047 return false;
11048 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11049 return EvalOK;
11050 }
11051
11052 private:
11053 SequenceChecker &Self;
11054 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011055 bool EvalOK = true;
11056 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000011057
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011058 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000011059 /// if any.
11060 Object getObject(Expr *E, bool Mod) const {
11061 E = E->IgnoreParenCasts();
11062 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11063 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11064 return getObject(UO->getSubExpr(), Mod);
11065 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11066 if (BO->getOpcode() == BO_Comma)
11067 return getObject(BO->getRHS(), Mod);
11068 if (Mod && BO->isAssignmentOp())
11069 return getObject(BO->getLHS(), Mod);
11070 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11071 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11072 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11073 return ME->getMemberDecl();
11074 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11075 // FIXME: If this is a reference, map through to its value.
11076 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000011077 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011078 }
11079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011080 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011081 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11082 Usage &U = UI.Uses[UK];
11083 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11084 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11085 ModAsSideEffect->push_back(std::make_pair(O, U));
11086 U.Use = Ref;
11087 U.Seq = Region;
11088 }
11089 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011090
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011091 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011092 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11093 bool IsModMod) {
11094 if (UI.Diagnosed)
11095 return;
11096
11097 const Usage &U = UI.Uses[OtherKind];
11098 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11099 return;
11100
11101 Expr *Mod = U.Use;
11102 Expr *ModOrUse = Ref;
11103 if (OtherKind == UK_Use)
11104 std::swap(Mod, ModOrUse);
11105
11106 SemaRef.Diag(Mod->getExprLoc(),
11107 IsModMod ? diag::warn_unsequenced_mod_mod
11108 : diag::warn_unsequenced_mod_use)
11109 << O << SourceRange(ModOrUse->getExprLoc());
11110 UI.Diagnosed = true;
11111 }
11112
11113 void notePreUse(Object O, Expr *Use) {
11114 UsageInfo &U = UsageMap[O];
11115 // Uses conflict with other modifications.
11116 checkUsage(O, U, Use, UK_ModAsValue, false);
11117 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011118
Richard Smithc406cb72013-01-17 01:17:56 +000011119 void notePostUse(Object O, Expr *Use) {
11120 UsageInfo &U = UsageMap[O];
11121 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11122 addUsage(U, O, Use, UK_Use);
11123 }
11124
11125 void notePreMod(Object O, Expr *Mod) {
11126 UsageInfo &U = UsageMap[O];
11127 // Modifications conflict with other modifications and with uses.
11128 checkUsage(O, U, Mod, UK_ModAsValue, true);
11129 checkUsage(O, U, Mod, UK_Use, false);
11130 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011131
Richard Smithc406cb72013-01-17 01:17:56 +000011132 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11133 UsageInfo &U = UsageMap[O];
11134 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11135 addUsage(U, O, Use, UK);
11136 }
11137
11138public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011139 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011140 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011141 Visit(E);
11142 }
11143
11144 void VisitStmt(Stmt *S) {
11145 // Skip all statements which aren't expressions for now.
11146 }
11147
11148 void VisitExpr(Expr *E) {
11149 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011150 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011151 }
11152
11153 void VisitCastExpr(CastExpr *E) {
11154 Object O = Object();
11155 if (E->getCastKind() == CK_LValueToRValue)
11156 O = getObject(E->getSubExpr(), false);
11157
11158 if (O)
11159 notePreUse(O, E);
11160 VisitExpr(E);
11161 if (O)
11162 notePostUse(O, E);
11163 }
11164
11165 void VisitBinComma(BinaryOperator *BO) {
11166 // C++11 [expr.comma]p1:
11167 // Every value computation and side effect associated with the left
11168 // expression is sequenced before every value computation and side
11169 // effect associated with the right expression.
11170 SequenceTree::Seq LHS = Tree.allocate(Region);
11171 SequenceTree::Seq RHS = Tree.allocate(Region);
11172 SequenceTree::Seq OldRegion = Region;
11173
11174 {
11175 SequencedSubexpression SeqLHS(*this);
11176 Region = LHS;
11177 Visit(BO->getLHS());
11178 }
11179
11180 Region = RHS;
11181 Visit(BO->getRHS());
11182
11183 Region = OldRegion;
11184
11185 // Forget that LHS and RHS are sequenced. They are both unsequenced
11186 // with respect to other stuff.
11187 Tree.merge(LHS);
11188 Tree.merge(RHS);
11189 }
11190
11191 void VisitBinAssign(BinaryOperator *BO) {
11192 // The modification is sequenced after the value computation of the LHS
11193 // and RHS, so check it before inspecting the operands and update the
11194 // map afterwards.
11195 Object O = getObject(BO->getLHS(), true);
11196 if (!O)
11197 return VisitExpr(BO);
11198
11199 notePreMod(O, BO);
11200
11201 // C++11 [expr.ass]p7:
11202 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11203 // only once.
11204 //
11205 // Therefore, for a compound assignment operator, O is considered used
11206 // everywhere except within the evaluation of E1 itself.
11207 if (isa<CompoundAssignOperator>(BO))
11208 notePreUse(O, BO);
11209
11210 Visit(BO->getLHS());
11211
11212 if (isa<CompoundAssignOperator>(BO))
11213 notePostUse(O, BO);
11214
11215 Visit(BO->getRHS());
11216
Richard Smith83e37bee2013-06-26 23:16:51 +000011217 // C++11 [expr.ass]p1:
11218 // the assignment is sequenced [...] before the value computation of the
11219 // assignment expression.
11220 // C11 6.5.16/3 has no such rule.
11221 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11222 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011223 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011224
Richard Smithc406cb72013-01-17 01:17:56 +000011225 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11226 VisitBinAssign(CAO);
11227 }
11228
11229 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11230 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11231 void VisitUnaryPreIncDec(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());
Richard Smith83e37bee2013-06-26 23:16:51 +000011238 // C++11 [expr.pre.incr]p1:
11239 // the expression ++x is equivalent to x+=1
11240 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11241 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011242 }
11243
11244 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11245 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11246 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11247 Object O = getObject(UO->getSubExpr(), true);
11248 if (!O)
11249 return VisitExpr(UO);
11250
11251 notePreMod(O, UO);
11252 Visit(UO->getSubExpr());
11253 notePostMod(O, UO, UK_ModAsSideEffect);
11254 }
11255
11256 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11257 void VisitBinLOr(BinaryOperator *BO) {
11258 // The side-effects of the LHS of an '&&' are sequenced before the
11259 // value computation of the RHS, and hence before the value computation
11260 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11261 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011262 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011263 {
11264 SequencedSubexpression Sequenced(*this);
11265 Visit(BO->getLHS());
11266 }
11267
11268 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011269 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011270 if (!Result)
11271 Visit(BO->getRHS());
11272 } else {
11273 // Check for unsequenced operations in the RHS, treating it as an
11274 // entirely separate evaluation.
11275 //
11276 // FIXME: If there are operations in the RHS which are unsequenced
11277 // with respect to operations outside the RHS, and those operations
11278 // are unconditionally evaluated, diagnose them.
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 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011283 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011284 {
11285 SequencedSubexpression Sequenced(*this);
11286 Visit(BO->getLHS());
11287 }
11288
11289 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011290 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011291 if (Result)
11292 Visit(BO->getRHS());
11293 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011294 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011295 }
Richard Smithc406cb72013-01-17 01:17:56 +000011296 }
11297
11298 // Only visit the condition, unless we can be sure which subexpression will
11299 // be chosen.
11300 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011301 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011302 {
11303 SequencedSubexpression Sequenced(*this);
11304 Visit(CO->getCond());
11305 }
Richard Smithc406cb72013-01-17 01:17:56 +000011306
11307 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011308 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011309 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011310 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011311 WorkList.push_back(CO->getTrueExpr());
11312 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011313 }
Richard Smithc406cb72013-01-17 01:17:56 +000011314 }
11315
Richard Smithe3dbfe02013-06-30 10:40:20 +000011316 void VisitCallExpr(CallExpr *CE) {
11317 // C++11 [intro.execution]p15:
11318 // When calling a function [...], every value computation and side effect
11319 // associated with any argument expression, or with the postfix expression
11320 // designating the called function, is sequenced before execution of every
11321 // expression or statement in the body of the function [and thus before
11322 // the value computation of its result].
11323 SequencedSubexpression Sequenced(*this);
11324 Base::VisitCallExpr(CE);
11325
11326 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11327 }
11328
Richard Smithc406cb72013-01-17 01:17:56 +000011329 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011330 // This is a call, so all subexpressions are sequenced before the result.
11331 SequencedSubexpression Sequenced(*this);
11332
Richard Smithc406cb72013-01-17 01:17:56 +000011333 if (!CCE->isListInitialization())
11334 return VisitExpr(CCE);
11335
11336 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011337 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011338 SequenceTree::Seq Parent = Region;
11339 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11340 E = CCE->arg_end();
11341 I != E; ++I) {
11342 Region = Tree.allocate(Parent);
11343 Elts.push_back(Region);
11344 Visit(*I);
11345 }
11346
11347 // Forget that the initializers are sequenced.
11348 Region = Parent;
11349 for (unsigned I = 0; I < Elts.size(); ++I)
11350 Tree.merge(Elts[I]);
11351 }
11352
11353 void VisitInitListExpr(InitListExpr *ILE) {
11354 if (!SemaRef.getLangOpts().CPlusPlus11)
11355 return VisitExpr(ILE);
11356
11357 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011358 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011359 SequenceTree::Seq Parent = Region;
11360 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11361 Expr *E = ILE->getInit(I);
11362 if (!E) continue;
11363 Region = Tree.allocate(Parent);
11364 Elts.push_back(Region);
11365 Visit(E);
11366 }
11367
11368 // Forget that the initializers are sequenced.
11369 Region = Parent;
11370 for (unsigned I = 0; I < Elts.size(); ++I)
11371 Tree.merge(Elts[I]);
11372 }
11373};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011374
11375} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011376
11377void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011378 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011379 WorkList.push_back(E);
11380 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011381 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011382 SequenceChecker(*this, Item, WorkList);
11383 }
Richard Smithc406cb72013-01-17 01:17:56 +000011384}
11385
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011386void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11387 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011388 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011389 if (!E->isInstantiationDependent())
11390 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011391 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011392 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011393 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011394}
11395
John McCall1f425642010-11-11 03:21:53 +000011396void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11397 FieldDecl *BitField,
11398 Expr *Init) {
11399 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11400}
11401
David Majnemer61a5bbf2015-04-07 22:08:51 +000011402static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11403 SourceLocation Loc) {
11404 if (!PType->isVariablyModifiedType())
11405 return;
11406 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11407 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11408 return;
11409 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011410 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11411 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11412 return;
11413 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011414 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11415 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11416 return;
11417 }
11418
11419 const ArrayType *AT = S.Context.getAsArrayType(PType);
11420 if (!AT)
11421 return;
11422
11423 if (AT->getSizeModifier() != ArrayType::Star) {
11424 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11425 return;
11426 }
11427
11428 S.Diag(Loc, diag::err_array_star_in_function_definition);
11429}
11430
Mike Stump0c2ec772010-01-21 03:59:47 +000011431/// CheckParmsForFunctionDef - Check that the parameters of the given
11432/// function are appropriate for the definition of a function. This
11433/// takes care of any checks that cannot be performed on the
11434/// declaration itself, e.g., that the types of each of the function
11435/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011436bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011437 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011438 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011439 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011440 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11441 // function declarator that is part of a function definition of
11442 // that function shall not have incomplete type.
11443 //
11444 // This is also C++ [dcl.fct]p6.
11445 if (!Param->isInvalidDecl() &&
11446 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011447 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011448 Param->setInvalidDecl();
11449 HasInvalidParm = true;
11450 }
11451
11452 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11453 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011454 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011455 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011456 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011457 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011458 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011459
11460 // C99 6.7.5.3p12:
11461 // If the function declarator is not part of a definition of that
11462 // function, parameters may have incomplete type and may use the [*]
11463 // notation in their sequences of declarator specifiers to specify
11464 // variable length array types.
11465 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011466 // FIXME: This diagnostic should point the '[*]' if source-location
11467 // information is added for it.
11468 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011469
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011470 // If the parameter is a c++ class type and it has to be destructed in the
11471 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011472 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011473 if (!Param->isInvalidDecl()) {
11474 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11475 if (!ClassDecl->isInvalidDecl() &&
11476 !ClassDecl->hasIrrelevantDestructor() &&
11477 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011478 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011479 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11480 MarkFunctionReferenced(Param->getLocation(), Destructor);
11481 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011482 }
11483 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011484 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011485
11486 // Parameters with the pass_object_size attribute only need to be marked
11487 // constant at function definitions. Because we lack information about
11488 // whether we're on a declaration or definition when we're instantiating the
11489 // attribute, we need to check for constness here.
11490 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11491 if (!Param->getType().isConstQualified())
11492 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11493 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011494 }
11495
11496 return HasInvalidParm;
11497}
John McCall2b5c1b22010-08-12 21:44:57 +000011498
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011499/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11500/// or MemberExpr.
11501static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11502 ASTContext &Context) {
11503 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11504 return Context.getDeclAlign(DRE->getDecl());
11505
11506 if (const auto *ME = dyn_cast<MemberExpr>(E))
11507 return Context.getDeclAlign(ME->getMemberDecl());
11508
11509 return TypeAlign;
11510}
11511
John McCall2b5c1b22010-08-12 21:44:57 +000011512/// CheckCastAlign - Implements -Wcast-align, which warns when a
11513/// pointer cast increases the alignment requirements.
11514void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11515 // This is actually a lot of work to potentially be doing on every
11516 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011517 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011518 return;
11519
11520 // Ignore dependent types.
11521 if (T->isDependentType() || Op->getType()->isDependentType())
11522 return;
11523
11524 // Require that the destination be a pointer type.
11525 const PointerType *DestPtr = T->getAs<PointerType>();
11526 if (!DestPtr) return;
11527
11528 // If the destination has alignment 1, we're done.
11529 QualType DestPointee = DestPtr->getPointeeType();
11530 if (DestPointee->isIncompleteType()) return;
11531 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11532 if (DestAlign.isOne()) return;
11533
11534 // Require that the source be a pointer type.
11535 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11536 if (!SrcPtr) return;
11537 QualType SrcPointee = SrcPtr->getPointeeType();
11538
11539 // Whitelist casts from cv void*. We already implicitly
11540 // whitelisted casts to cv void*, since they have alignment 1.
11541 // Also whitelist casts involving incomplete types, which implicitly
11542 // includes 'void'.
11543 if (SrcPointee->isIncompleteType()) return;
11544
11545 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011546
11547 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11548 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11549 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11550 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11551 if (UO->getOpcode() == UO_AddrOf)
11552 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11553 }
11554
John McCall2b5c1b22010-08-12 21:44:57 +000011555 if (SrcAlign >= DestAlign) return;
11556
11557 Diag(TRange.getBegin(), diag::warn_cast_align)
11558 << Op->getType() << T
11559 << static_cast<unsigned>(SrcAlign.getQuantity())
11560 << static_cast<unsigned>(DestAlign.getQuantity())
11561 << TRange << Op->getSourceRange();
11562}
11563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011564/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011565/// array member of a struct.
11566///
11567/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11568/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011569static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011570 const NamedDecl *ND) {
11571 if (Size != 1 || !ND) return false;
11572
11573 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11574 if (!FD) return false;
11575
11576 // Don't consider sizes resulting from macro expansions or template argument
11577 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011578
11579 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011580 while (TInfo) {
11581 TypeLoc TL = TInfo->getTypeLoc();
11582 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011583 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11584 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011585 TInfo = TDL->getTypeSourceInfo();
11586 continue;
11587 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011588 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11589 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011590 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11591 return false;
11592 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011593 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011594 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011595
11596 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011597 if (!RD) return false;
11598 if (RD->isUnion()) return false;
11599 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11600 if (!CRD->isStandardLayout()) return false;
11601 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011602
Benjamin Kramer8c543672011-08-06 03:04:42 +000011603 // See if this is the last field decl in the record.
11604 const Decl *D = FD;
11605 while ((D = D->getNextDeclInContext()))
11606 if (isa<FieldDecl>(D))
11607 return false;
11608 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011609}
11610
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011611void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011612 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011613 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011614 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011615 if (IndexExpr->isValueDependent())
11616 return;
11617
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011618 const Type *EffectiveType =
11619 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011620 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011621 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011622 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011623 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011624 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011625
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011626 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011627 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011628 return;
Richard Smith13f67182011-12-16 19:31:14 +000011629 if (IndexNegated)
11630 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011631
Craig Topperc3ec1492014-05-26 06:22:03 +000011632 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011633 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011634 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011635 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011636 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011637
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011638 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011639 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011640 if (!size.isStrictlyPositive())
11641 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011642
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011643 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011644 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011645 // Make sure we're comparing apples to apples when comparing index to size
11646 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11647 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011648 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011649 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011650 if (ptrarith_typesize != array_typesize) {
11651 // There's a cast to a different size type involved
11652 uint64_t ratio = array_typesize / ptrarith_typesize;
11653 // TODO: Be smarter about handling cases where array_typesize is not a
11654 // multiple of ptrarith_typesize
11655 if (ptrarith_typesize * ratio == array_typesize)
11656 size *= llvm::APInt(size.getBitWidth(), ratio);
11657 }
11658 }
11659
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011660 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011661 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011662 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011663 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011664
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011665 // For array subscripting the index must be less than size, but for pointer
11666 // arithmetic also allow the index (offset) to be equal to size since
11667 // computing the next address after the end of the array is legal and
11668 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011669 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011670 return;
11671
11672 // Also don't warn for arrays of size 1 which are members of some
11673 // structure. These are often used to approximate flexible arrays in C89
11674 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011675 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011676 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011677
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011678 // Suppress the warning if the subscript expression (as identified by the
11679 // ']' location) and the index expression are both from macro expansions
11680 // within a system header.
11681 if (ASE) {
11682 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11683 ASE->getRBracketLoc());
11684 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11685 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11686 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011687 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011688 return;
11689 }
11690 }
11691
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011692 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011693 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011694 DiagID = diag::warn_array_index_exceeds_bounds;
11695
11696 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11697 PDiag(DiagID) << index.toString(10, true)
11698 << size.toString(10, true)
11699 << (unsigned)size.getLimitedValue(~0U)
11700 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011701 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011702 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011703 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011704 DiagID = diag::warn_ptr_arith_precedes_bounds;
11705 if (index.isNegative()) index = -index;
11706 }
11707
11708 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11709 PDiag(DiagID) << index.toString(10, true)
11710 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011711 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011712
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011713 if (!ND) {
11714 // Try harder to find a NamedDecl to point at in the note.
11715 while (const ArraySubscriptExpr *ASE =
11716 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11717 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11718 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011719 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011720 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011721 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011722 }
11723
Chandler Carruth1af88f12011-02-17 21:10:52 +000011724 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011725 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11726 PDiag(diag::note_array_index_out_of_bounds)
11727 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011728}
11729
Ted Kremenekdf26df72011-03-01 18:41:00 +000011730void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011731 int AllowOnePastEnd = 0;
11732 while (expr) {
11733 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011734 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011735 case Stmt::ArraySubscriptExprClass: {
11736 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011737 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011738 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011739 expr = ASE->getBase();
11740 break;
11741 }
11742 case Stmt::MemberExprClass: {
11743 expr = cast<MemberExpr>(expr)->getBase();
11744 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011745 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011746 case Stmt::OMPArraySectionExprClass: {
11747 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11748 if (ASE->getLowerBound())
11749 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11750 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11751 return;
11752 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011753 case Stmt::UnaryOperatorClass: {
11754 // Only unwrap the * and & unary operators
11755 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11756 expr = UO->getSubExpr();
11757 switch (UO->getOpcode()) {
11758 case UO_AddrOf:
11759 AllowOnePastEnd++;
11760 break;
11761 case UO_Deref:
11762 AllowOnePastEnd--;
11763 break;
11764 default:
11765 return;
11766 }
11767 break;
11768 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011769 case Stmt::ConditionalOperatorClass: {
11770 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11771 if (const Expr *lhs = cond->getLHS())
11772 CheckArrayAccess(lhs);
11773 if (const Expr *rhs = cond->getRHS())
11774 CheckArrayAccess(rhs);
11775 return;
11776 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011777 case Stmt::CXXOperatorCallExprClass: {
11778 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11779 for (const auto *Arg : OCE->arguments())
11780 CheckArrayAccess(Arg);
11781 return;
11782 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011783 default:
11784 return;
11785 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011786 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011787}
John McCall31168b02011-06-15 23:02:42 +000011788
11789//===--- CHECK: Objective-C retain cycles ----------------------------------//
11790
11791namespace {
John McCall31168b02011-06-15 23:02:42 +000011792
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011793struct RetainCycleOwner {
11794 VarDecl *Variable = nullptr;
11795 SourceRange Range;
11796 SourceLocation Loc;
11797 bool Indirect = false;
11798
11799 RetainCycleOwner() = default;
11800
11801 void setLocsFrom(Expr *e) {
11802 Loc = e->getExprLoc();
11803 Range = e->getSourceRange();
11804 }
11805};
11806
11807} // namespace
John McCall31168b02011-06-15 23:02:42 +000011808
11809/// Consider whether capturing the given variable can possibly lead to
11810/// a retain cycle.
11811static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011812 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011813 // lifetime. In MRR, it's captured strongly if the variable is
11814 // __block and has an appropriate type.
11815 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11816 return false;
11817
11818 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011819 if (ref)
11820 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011821 return true;
11822}
11823
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011824static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011825 while (true) {
11826 e = e->IgnoreParens();
11827 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11828 switch (cast->getCastKind()) {
11829 case CK_BitCast:
11830 case CK_LValueBitCast:
11831 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011832 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011833 e = cast->getSubExpr();
11834 continue;
11835
John McCall31168b02011-06-15 23:02:42 +000011836 default:
11837 return false;
11838 }
11839 }
11840
11841 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11842 ObjCIvarDecl *ivar = ref->getDecl();
11843 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11844 return false;
11845
11846 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011847 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011848 return false;
11849
11850 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11851 owner.Indirect = true;
11852 return true;
11853 }
11854
11855 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11856 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11857 if (!var) return false;
11858 return considerVariable(var, ref, owner);
11859 }
11860
John McCall31168b02011-06-15 23:02:42 +000011861 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11862 if (member->isArrow()) return false;
11863
11864 // Don't count this as an indirect ownership.
11865 e = member->getBase();
11866 continue;
11867 }
11868
John McCallfe96e0b2011-11-06 09:01:30 +000011869 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11870 // Only pay attention to pseudo-objects on property references.
11871 ObjCPropertyRefExpr *pre
11872 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11873 ->IgnoreParens());
11874 if (!pre) return false;
11875 if (pre->isImplicitProperty()) return false;
11876 ObjCPropertyDecl *property = pre->getExplicitProperty();
11877 if (!property->isRetaining() &&
11878 !(property->getPropertyIvarDecl() &&
11879 property->getPropertyIvarDecl()->getType()
11880 .getObjCLifetime() == Qualifiers::OCL_Strong))
11881 return false;
11882
11883 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011884 if (pre->isSuperReceiver()) {
11885 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11886 if (!owner.Variable)
11887 return false;
11888 owner.Loc = pre->getLocation();
11889 owner.Range = pre->getSourceRange();
11890 return true;
11891 }
John McCallfe96e0b2011-11-06 09:01:30 +000011892 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11893 ->getSourceExpr());
11894 continue;
11895 }
11896
John McCall31168b02011-06-15 23:02:42 +000011897 // Array ivars?
11898
11899 return false;
11900 }
11901}
11902
11903namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011904
John McCall31168b02011-06-15 23:02:42 +000011905 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011906 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011907 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011908 Expr *Capturer = nullptr;
11909 bool VarWillBeReased = false;
11910
11911 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11912 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11913 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011914
11915 void VisitDeclRefExpr(DeclRefExpr *ref) {
11916 if (ref->getDecl() == Variable && !Capturer)
11917 Capturer = ref;
11918 }
11919
John McCall31168b02011-06-15 23:02:42 +000011920 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11921 if (Capturer) return;
11922 Visit(ref->getBase());
11923 if (Capturer && ref->isFreeIvar())
11924 Capturer = ref;
11925 }
11926
11927 void VisitBlockExpr(BlockExpr *block) {
11928 // Look inside nested blocks
11929 if (block->getBlockDecl()->capturesVariable(Variable))
11930 Visit(block->getBlockDecl()->getBody());
11931 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011932
11933 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11934 if (Capturer) return;
11935 if (OVE->getSourceExpr())
11936 Visit(OVE->getSourceExpr());
11937 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011938
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011939 void VisitBinaryOperator(BinaryOperator *BinOp) {
11940 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11941 return;
11942 Expr *LHS = BinOp->getLHS();
11943 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11944 if (DRE->getDecl() != Variable)
11945 return;
11946 if (Expr *RHS = BinOp->getRHS()) {
11947 RHS = RHS->IgnoreParenCasts();
11948 llvm::APSInt Value;
11949 VarWillBeReased =
11950 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11951 }
11952 }
11953 }
John McCall31168b02011-06-15 23:02:42 +000011954 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011955
11956} // namespace
John McCall31168b02011-06-15 23:02:42 +000011957
11958/// Check whether the given argument is a block which captures a
11959/// variable.
11960static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11961 assert(owner.Variable && owner.Loc.isValid());
11962
11963 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011964
11965 // Look through [^{...} copy] and Block_copy(^{...}).
11966 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11967 Selector Cmd = ME->getSelector();
11968 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11969 e = ME->getInstanceReceiver();
11970 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011971 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011972 e = e->IgnoreParenCasts();
11973 }
11974 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11975 if (CE->getNumArgs() == 1) {
11976 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011977 if (Fn) {
11978 const IdentifierInfo *FnI = Fn->getIdentifier();
11979 if (FnI && FnI->isStr("_Block_copy")) {
11980 e = CE->getArg(0)->IgnoreParenCasts();
11981 }
11982 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011983 }
11984 }
11985
John McCall31168b02011-06-15 23:02:42 +000011986 BlockExpr *block = dyn_cast<BlockExpr>(e);
11987 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011988 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011989
11990 FindCaptureVisitor visitor(S.Context, owner.Variable);
11991 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011992 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011993}
11994
11995static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11996 RetainCycleOwner &owner) {
11997 assert(capturer);
11998 assert(owner.Variable && owner.Loc.isValid());
11999
12000 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12001 << owner.Variable << capturer->getSourceRange();
12002 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12003 << owner.Indirect << owner.Range;
12004}
12005
12006/// Check for a keyword selector that starts with the word 'add' or
12007/// 'set'.
12008static bool isSetterLikeSelector(Selector sel) {
12009 if (sel.isUnarySelector()) return false;
12010
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012011 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000012012 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012013 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000012014 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012015 else if (str.startswith("add")) {
12016 // Specially whitelist 'addOperationWithBlock:'.
12017 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12018 return false;
12019 str = str.substr(3);
12020 }
John McCall31168b02011-06-15 23:02:42 +000012021 else
12022 return false;
12023
12024 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000012025 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000012026}
12027
Benjamin Kramer3a743452015-03-09 15:03:32 +000012028static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12029 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012030 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12031 Message->getReceiverInterface(),
12032 NSAPI::ClassId_NSMutableArray);
12033 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012034 return None;
12035 }
12036
12037 Selector Sel = Message->getSelector();
12038
12039 Optional<NSAPI::NSArrayMethodKind> MKOpt =
12040 S.NSAPIObj->getNSArrayMethodKind(Sel);
12041 if (!MKOpt) {
12042 return None;
12043 }
12044
12045 NSAPI::NSArrayMethodKind MK = *MKOpt;
12046
12047 switch (MK) {
12048 case NSAPI::NSMutableArr_addObject:
12049 case NSAPI::NSMutableArr_insertObjectAtIndex:
12050 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12051 return 0;
12052 case NSAPI::NSMutableArr_replaceObjectAtIndex:
12053 return 1;
12054
12055 default:
12056 return None;
12057 }
12058
12059 return None;
12060}
12061
12062static
12063Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12064 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012065 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12066 Message->getReceiverInterface(),
12067 NSAPI::ClassId_NSMutableDictionary);
12068 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012069 return None;
12070 }
12071
12072 Selector Sel = Message->getSelector();
12073
12074 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12075 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12076 if (!MKOpt) {
12077 return None;
12078 }
12079
12080 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12081
12082 switch (MK) {
12083 case NSAPI::NSMutableDict_setObjectForKey:
12084 case NSAPI::NSMutableDict_setValueForKey:
12085 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12086 return 0;
12087
12088 default:
12089 return None;
12090 }
12091
12092 return None;
12093}
12094
12095static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012096 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12097 Message->getReceiverInterface(),
12098 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012099
Alex Denisov5dfac812015-08-06 04:51:14 +000012100 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12101 Message->getReceiverInterface(),
12102 NSAPI::ClassId_NSMutableOrderedSet);
12103 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012104 return None;
12105 }
12106
12107 Selector Sel = Message->getSelector();
12108
12109 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12110 if (!MKOpt) {
12111 return None;
12112 }
12113
12114 NSAPI::NSSetMethodKind MK = *MKOpt;
12115
12116 switch (MK) {
12117 case NSAPI::NSMutableSet_addObject:
12118 case NSAPI::NSOrderedSet_setObjectAtIndex:
12119 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12120 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12121 return 0;
12122 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12123 return 1;
12124 }
12125
12126 return None;
12127}
12128
12129void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12130 if (!Message->isInstanceMessage()) {
12131 return;
12132 }
12133
12134 Optional<int> ArgOpt;
12135
12136 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12137 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12138 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12139 return;
12140 }
12141
12142 int ArgIndex = *ArgOpt;
12143
Alex Denisove1d882c2015-03-04 17:55:52 +000012144 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12145 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12146 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12147 }
12148
Alex Denisov5dfac812015-08-06 04:51:14 +000012149 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012150 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012151 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012152 Diag(Message->getSourceRange().getBegin(),
12153 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012154 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012155 }
12156 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012157 } else {
12158 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12159
12160 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12161 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12162 }
12163
12164 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12165 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12166 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12167 ValueDecl *Decl = ReceiverRE->getDecl();
12168 Diag(Message->getSourceRange().getBegin(),
12169 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012170 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012171 if (!ArgRE->isObjCSelfExpr()) {
12172 Diag(Decl->getLocation(),
12173 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012174 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012175 }
12176 }
12177 }
12178 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12179 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12180 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12181 ObjCIvarDecl *Decl = IvarRE->getDecl();
12182 Diag(Message->getSourceRange().getBegin(),
12183 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012184 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012185 Diag(Decl->getLocation(),
12186 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012187 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012188 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012189 }
12190 }
12191 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012192}
12193
John McCall31168b02011-06-15 23:02:42 +000012194/// Check a message send to see if it's likely to cause a retain cycle.
12195void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12196 // Only check instance methods whose selector looks like a setter.
12197 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12198 return;
12199
12200 // Try to find a variable that the receiver is strongly owned by.
12201 RetainCycleOwner owner;
12202 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012203 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012204 return;
12205 } else {
12206 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12207 owner.Variable = getCurMethodDecl()->getSelfDecl();
12208 owner.Loc = msg->getSuperLoc();
12209 owner.Range = msg->getSuperLoc();
12210 }
12211
12212 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012213 const ObjCMethodDecl *MD = msg->getMethodDecl();
12214 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12215 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12216 // noescape blocks should not be retained by the method.
12217 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12218 continue;
John McCall31168b02011-06-15 23:02:42 +000012219 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012220 }
12221 }
John McCall31168b02011-06-15 23:02:42 +000012222}
12223
12224/// Check a property assign to see if it's likely to cause a retain cycle.
12225void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12226 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012227 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012228 return;
12229
12230 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12231 diagnoseRetainCycle(*this, capturer, owner);
12232}
12233
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012234void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12235 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012236 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012237 return;
12238
12239 // Because we don't have an expression for the variable, we have to set the
12240 // location explicitly here.
12241 Owner.Loc = Var->getLocation();
12242 Owner.Range = Var->getSourceRange();
12243
12244 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12245 diagnoseRetainCycle(*this, Capturer, Owner);
12246}
12247
Ted Kremenek9304da92012-12-21 08:04:28 +000012248static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12249 Expr *RHS, bool isProperty) {
12250 // Check if RHS is an Objective-C object literal, which also can get
12251 // immediately zapped in a weak reference. Note that we explicitly
12252 // allow ObjCStringLiterals, since those are designed to never really die.
12253 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012254
Ted Kremenek64873352012-12-21 22:46:35 +000012255 // This enum needs to match with the 'select' in
12256 // warn_objc_arc_literal_assign (off-by-1).
12257 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12258 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12259 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012260
12261 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012262 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012263 << (isProperty ? 0 : 1)
12264 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012265
12266 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012267}
12268
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012269static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12270 Qualifiers::ObjCLifetime LT,
12271 Expr *RHS, bool isProperty) {
12272 // Strip off any implicit cast added to get to the one ARC-specific.
12273 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12274 if (cast->getCastKind() == CK_ARCConsumeObject) {
12275 S.Diag(Loc, diag::warn_arc_retained_assign)
12276 << (LT == Qualifiers::OCL_ExplicitNone)
12277 << (isProperty ? 0 : 1)
12278 << RHS->getSourceRange();
12279 return true;
12280 }
12281 RHS = cast->getSubExpr();
12282 }
12283
12284 if (LT == Qualifiers::OCL_Weak &&
12285 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12286 return true;
12287
12288 return false;
12289}
12290
Ted Kremenekb36234d2012-12-21 08:04:20 +000012291bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12292 QualType LHS, Expr *RHS) {
12293 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12294
12295 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12296 return false;
12297
12298 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12299 return true;
12300
12301 return false;
12302}
12303
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012304void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12305 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012306 QualType LHSType;
12307 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012308 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012309 ObjCPropertyRefExpr *PRE
12310 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12311 if (PRE && !PRE->isImplicitProperty()) {
12312 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12313 if (PD)
12314 LHSType = PD->getType();
12315 }
12316
12317 if (LHSType.isNull())
12318 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012319
12320 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12321
12322 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012323 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012324 getCurFunction()->markSafeWeakUse(LHS);
12325 }
12326
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012327 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12328 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012329
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012330 // FIXME. Check for other life times.
12331 if (LT != Qualifiers::OCL_None)
12332 return;
12333
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012334 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012335 if (PRE->isImplicitProperty())
12336 return;
12337 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12338 if (!PD)
12339 return;
12340
Bill Wendling44426052012-12-20 19:22:21 +000012341 unsigned Attributes = PD->getPropertyAttributes();
12342 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012343 // when 'assign' attribute was not explicitly specified
12344 // by user, ignore it and rely on property type itself
12345 // for lifetime info.
12346 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12347 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12348 LHSType->isObjCRetainableType())
12349 return;
12350
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012351 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012352 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012353 Diag(Loc, diag::warn_arc_retained_property_assign)
12354 << RHS->getSourceRange();
12355 return;
12356 }
12357 RHS = cast->getSubExpr();
12358 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012359 }
Bill Wendling44426052012-12-20 19:22:21 +000012360 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012361 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12362 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012363 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012364 }
12365}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012366
12367//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12368
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012369static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12370 SourceLocation StmtLoc,
12371 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012372 // Do not warn if the body is a macro that expands to nothing, e.g:
12373 //
12374 // #define CALL(x)
12375 // if (condition)
12376 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012377 if (Body->hasLeadingEmptyMacro())
12378 return false;
12379
12380 // Get line numbers of statement and body.
12381 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012382 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012383 &StmtLineInvalid);
12384 if (StmtLineInvalid)
12385 return false;
12386
12387 bool BodyLineInvalid;
12388 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12389 &BodyLineInvalid);
12390 if (BodyLineInvalid)
12391 return false;
12392
12393 // Warn if null statement and body are on the same line.
12394 if (StmtLine != BodyLine)
12395 return false;
12396
12397 return true;
12398}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012399
12400void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12401 const Stmt *Body,
12402 unsigned DiagID) {
12403 // Since this is a syntactic check, don't emit diagnostic for template
12404 // instantiations, this just adds noise.
12405 if (CurrentInstantiationScope)
12406 return;
12407
12408 // The body should be a null statement.
12409 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12410 if (!NBody)
12411 return;
12412
12413 // Do the usual checks.
12414 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12415 return;
12416
12417 Diag(NBody->getSemiLoc(), DiagID);
12418 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12419}
12420
12421void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12422 const Stmt *PossibleBody) {
12423 assert(!CurrentInstantiationScope); // Ensured by caller
12424
12425 SourceLocation StmtLoc;
12426 const Stmt *Body;
12427 unsigned DiagID;
12428 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12429 StmtLoc = FS->getRParenLoc();
12430 Body = FS->getBody();
12431 DiagID = diag::warn_empty_for_body;
12432 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12433 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12434 Body = WS->getBody();
12435 DiagID = diag::warn_empty_while_body;
12436 } else
12437 return; // Neither `for' nor `while'.
12438
12439 // The body should be a null statement.
12440 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12441 if (!NBody)
12442 return;
12443
12444 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012445 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012446 return;
12447
12448 // Do the usual checks.
12449 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12450 return;
12451
12452 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12453 // noise level low, emit diagnostics only if for/while is followed by a
12454 // CompoundStmt, e.g.:
12455 // for (int i = 0; i < n; i++);
12456 // {
12457 // a(i);
12458 // }
12459 // or if for/while is followed by a statement with more indentation
12460 // than for/while itself:
12461 // for (int i = 0; i < n; i++);
12462 // a(i);
12463 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12464 if (!ProbableTypo) {
12465 bool BodyColInvalid;
12466 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12467 PossibleBody->getLocStart(),
12468 &BodyColInvalid);
12469 if (BodyColInvalid)
12470 return;
12471
12472 bool StmtColInvalid;
12473 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12474 S->getLocStart(),
12475 &StmtColInvalid);
12476 if (StmtColInvalid)
12477 return;
12478
12479 if (BodyCol > StmtCol)
12480 ProbableTypo = true;
12481 }
12482
12483 if (ProbableTypo) {
12484 Diag(NBody->getSemiLoc(), DiagID);
12485 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12486 }
12487}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012488
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012489//===--- CHECK: Warn on self move with std::move. -------------------------===//
12490
12491/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12492void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12493 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012494 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12495 return;
12496
Richard Smith51ec0cf2017-02-21 01:17:38 +000012497 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012498 return;
12499
12500 // Strip parens and casts away.
12501 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12502 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12503
12504 // Check for a call expression
12505 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12506 if (!CE || CE->getNumArgs() != 1)
12507 return;
12508
12509 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012510 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012511 return;
12512
12513 // Get argument from std::move
12514 RHSExpr = CE->getArg(0);
12515
12516 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12517 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12518
12519 // Two DeclRefExpr's, check that the decls are the same.
12520 if (LHSDeclRef && RHSDeclRef) {
12521 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12522 return;
12523 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12524 RHSDeclRef->getDecl()->getCanonicalDecl())
12525 return;
12526
12527 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12528 << LHSExpr->getSourceRange()
12529 << RHSExpr->getSourceRange();
12530 return;
12531 }
12532
12533 // Member variables require a different approach to check for self moves.
12534 // MemberExpr's are the same if every nested MemberExpr refers to the same
12535 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12536 // the base Expr's are CXXThisExpr's.
12537 const Expr *LHSBase = LHSExpr;
12538 const Expr *RHSBase = RHSExpr;
12539 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12540 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12541 if (!LHSME || !RHSME)
12542 return;
12543
12544 while (LHSME && RHSME) {
12545 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12546 RHSME->getMemberDecl()->getCanonicalDecl())
12547 return;
12548
12549 LHSBase = LHSME->getBase();
12550 RHSBase = RHSME->getBase();
12551 LHSME = dyn_cast<MemberExpr>(LHSBase);
12552 RHSME = dyn_cast<MemberExpr>(RHSBase);
12553 }
12554
12555 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12556 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12557 if (LHSDeclRef && RHSDeclRef) {
12558 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12559 return;
12560 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12561 RHSDeclRef->getDecl()->getCanonicalDecl())
12562 return;
12563
12564 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12565 << LHSExpr->getSourceRange()
12566 << RHSExpr->getSourceRange();
12567 return;
12568 }
12569
12570 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12571 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12572 << LHSExpr->getSourceRange()
12573 << RHSExpr->getSourceRange();
12574}
12575
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012576//===--- Layout compatibility ----------------------------------------------//
12577
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012578static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012579
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012580/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012581static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012582 // C++11 [dcl.enum] p8:
12583 // Two enumeration types are layout-compatible if they have the same
12584 // underlying type.
12585 return ED1->isComplete() && ED2->isComplete() &&
12586 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12587}
12588
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012589/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012590static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12591 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012592 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12593 return false;
12594
12595 if (Field1->isBitField() != Field2->isBitField())
12596 return false;
12597
12598 if (Field1->isBitField()) {
12599 // Make sure that the bit-fields are the same length.
12600 unsigned Bits1 = Field1->getBitWidthValue(C);
12601 unsigned Bits2 = Field2->getBitWidthValue(C);
12602
12603 if (Bits1 != Bits2)
12604 return false;
12605 }
12606
12607 return true;
12608}
12609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012610/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012611/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012612static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12613 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012614 // If both records are C++ classes, check that base classes match.
12615 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12616 // If one of records is a CXXRecordDecl we are in C++ mode,
12617 // thus the other one is a CXXRecordDecl, too.
12618 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12619 // Check number of base classes.
12620 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12621 return false;
12622
12623 // Check the base classes.
12624 for (CXXRecordDecl::base_class_const_iterator
12625 Base1 = D1CXX->bases_begin(),
12626 BaseEnd1 = D1CXX->bases_end(),
12627 Base2 = D2CXX->bases_begin();
12628 Base1 != BaseEnd1;
12629 ++Base1, ++Base2) {
12630 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12631 return false;
12632 }
12633 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12634 // If only RD2 is a C++ class, it should have zero base classes.
12635 if (D2CXX->getNumBases() > 0)
12636 return false;
12637 }
12638
12639 // Check the fields.
12640 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12641 Field2End = RD2->field_end(),
12642 Field1 = RD1->field_begin(),
12643 Field1End = RD1->field_end();
12644 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12645 if (!isLayoutCompatible(C, *Field1, *Field2))
12646 return false;
12647 }
12648 if (Field1 != Field1End || Field2 != Field2End)
12649 return false;
12650
12651 return true;
12652}
12653
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012654/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012655/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012656static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12657 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012658 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012659 for (auto *Field2 : RD2->fields())
12660 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012661
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012662 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012663 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12664 I = UnmatchedFields.begin(),
12665 E = UnmatchedFields.end();
12666
12667 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012668 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012669 bool Result = UnmatchedFields.erase(*I);
12670 (void) Result;
12671 assert(Result);
12672 break;
12673 }
12674 }
12675 if (I == E)
12676 return false;
12677 }
12678
12679 return UnmatchedFields.empty();
12680}
12681
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012682static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12683 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012684 if (RD1->isUnion() != RD2->isUnion())
12685 return false;
12686
12687 if (RD1->isUnion())
12688 return isLayoutCompatibleUnion(C, RD1, RD2);
12689 else
12690 return isLayoutCompatibleStruct(C, RD1, RD2);
12691}
12692
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012693/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012694static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012695 if (T1.isNull() || T2.isNull())
12696 return false;
12697
12698 // C++11 [basic.types] p11:
12699 // If two types T1 and T2 are the same type, then T1 and T2 are
12700 // layout-compatible types.
12701 if (C.hasSameType(T1, T2))
12702 return true;
12703
12704 T1 = T1.getCanonicalType().getUnqualifiedType();
12705 T2 = T2.getCanonicalType().getUnqualifiedType();
12706
12707 const Type::TypeClass TC1 = T1->getTypeClass();
12708 const Type::TypeClass TC2 = T2->getTypeClass();
12709
12710 if (TC1 != TC2)
12711 return false;
12712
12713 if (TC1 == Type::Enum) {
12714 return isLayoutCompatible(C,
12715 cast<EnumType>(T1)->getDecl(),
12716 cast<EnumType>(T2)->getDecl());
12717 } else if (TC1 == Type::Record) {
12718 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12719 return false;
12720
12721 return isLayoutCompatible(C,
12722 cast<RecordType>(T1)->getDecl(),
12723 cast<RecordType>(T2)->getDecl());
12724 }
12725
12726 return false;
12727}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012728
12729//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12730
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012731/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012732///
12733/// \param TypeExpr Type tag expression, as it appears in user's code.
12734///
12735/// \param VD Declaration of an identifier that appears in a type tag.
12736///
12737/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012738static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12739 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012740 while(true) {
12741 if (!TypeExpr)
12742 return false;
12743
12744 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12745
12746 switch (TypeExpr->getStmtClass()) {
12747 case Stmt::UnaryOperatorClass: {
12748 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12749 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12750 TypeExpr = UO->getSubExpr();
12751 continue;
12752 }
12753 return false;
12754 }
12755
12756 case Stmt::DeclRefExprClass: {
12757 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12758 *VD = DRE->getDecl();
12759 return true;
12760 }
12761
12762 case Stmt::IntegerLiteralClass: {
12763 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12764 llvm::APInt MagicValueAPInt = IL->getValue();
12765 if (MagicValueAPInt.getActiveBits() <= 64) {
12766 *MagicValue = MagicValueAPInt.getZExtValue();
12767 return true;
12768 } else
12769 return false;
12770 }
12771
12772 case Stmt::BinaryConditionalOperatorClass:
12773 case Stmt::ConditionalOperatorClass: {
12774 const AbstractConditionalOperator *ACO =
12775 cast<AbstractConditionalOperator>(TypeExpr);
12776 bool Result;
12777 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12778 if (Result)
12779 TypeExpr = ACO->getTrueExpr();
12780 else
12781 TypeExpr = ACO->getFalseExpr();
12782 continue;
12783 }
12784 return false;
12785 }
12786
12787 case Stmt::BinaryOperatorClass: {
12788 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12789 if (BO->getOpcode() == BO_Comma) {
12790 TypeExpr = BO->getRHS();
12791 continue;
12792 }
12793 return false;
12794 }
12795
12796 default:
12797 return false;
12798 }
12799 }
12800}
12801
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012802/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012803///
12804/// \param TypeExpr Expression that specifies a type tag.
12805///
12806/// \param MagicValues Registered magic values.
12807///
12808/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12809/// kind.
12810///
12811/// \param TypeInfo Information about the corresponding C type.
12812///
12813/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012814static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012815 const IdentifierInfo *ArgumentKind,
12816 const Expr *TypeExpr, const ASTContext &Ctx,
12817 const llvm::DenseMap<Sema::TypeTagMagicValue,
12818 Sema::TypeTagData> *MagicValues,
12819 bool &FoundWrongKind,
12820 Sema::TypeTagData &TypeInfo) {
12821 FoundWrongKind = false;
12822
12823 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012824 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012825
12826 uint64_t MagicValue;
12827
12828 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12829 return false;
12830
12831 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012832 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012833 if (I->getArgumentKind() != ArgumentKind) {
12834 FoundWrongKind = true;
12835 return false;
12836 }
12837 TypeInfo.Type = I->getMatchingCType();
12838 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12839 TypeInfo.MustBeNull = I->getMustBeNull();
12840 return true;
12841 }
12842 return false;
12843 }
12844
12845 if (!MagicValues)
12846 return false;
12847
12848 llvm::DenseMap<Sema::TypeTagMagicValue,
12849 Sema::TypeTagData>::const_iterator I =
12850 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12851 if (I == MagicValues->end())
12852 return false;
12853
12854 TypeInfo = I->second;
12855 return true;
12856}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012857
12858void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12859 uint64_t MagicValue, QualType Type,
12860 bool LayoutCompatible,
12861 bool MustBeNull) {
12862 if (!TypeTagForDatatypeMagicValues)
12863 TypeTagForDatatypeMagicValues.reset(
12864 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12865
12866 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12867 (*TypeTagForDatatypeMagicValues)[Magic] =
12868 TypeTagData(Type, LayoutCompatible, MustBeNull);
12869}
12870
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012871static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012872 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12873 if (!BT1)
12874 return false;
12875
12876 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12877 if (!BT2)
12878 return false;
12879
12880 BuiltinType::Kind T1Kind = BT1->getKind();
12881 BuiltinType::Kind T2Kind = BT2->getKind();
12882
12883 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12884 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12885 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12886 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12887}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012888
12889void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012890 const ArrayRef<const Expr *> ExprArgs,
12891 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012892 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12893 bool IsPointerAttr = Attr->getIsPointer();
12894
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012895 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012896 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12897 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012898 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012899 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012900 return;
12901 }
Joel E. Denny81508102018-03-13 14:51:22 +000012902 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012903 bool FoundWrongKind;
12904 TypeTagData TypeInfo;
12905 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12906 TypeTagForDatatypeMagicValues.get(),
12907 FoundWrongKind, TypeInfo)) {
12908 if (FoundWrongKind)
12909 Diag(TypeTagExpr->getExprLoc(),
12910 diag::warn_type_tag_for_datatype_wrong_kind)
12911 << TypeTagExpr->getSourceRange();
12912 return;
12913 }
12914
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012915 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012916 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12917 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012918 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012919 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012920 return;
12921 }
Joel E. Denny81508102018-03-13 14:51:22 +000012922 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012923 if (IsPointerAttr) {
12924 // Skip implicit cast of pointer to `void *' (as a function argument).
12925 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012926 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012927 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012928 ArgumentExpr = ICE->getSubExpr();
12929 }
12930 QualType ArgumentType = ArgumentExpr->getType();
12931
12932 // Passing a `void*' pointer shouldn't trigger a warning.
12933 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12934 return;
12935
12936 if (TypeInfo.MustBeNull) {
12937 // Type tag with matching void type requires a null pointer.
12938 if (!ArgumentExpr->isNullPointerConstant(Context,
12939 Expr::NPC_ValueDependentIsNotNull)) {
12940 Diag(ArgumentExpr->getExprLoc(),
12941 diag::warn_type_safety_null_pointer_required)
12942 << ArgumentKind->getName()
12943 << ArgumentExpr->getSourceRange()
12944 << TypeTagExpr->getSourceRange();
12945 }
12946 return;
12947 }
12948
12949 QualType RequiredType = TypeInfo.Type;
12950 if (IsPointerAttr)
12951 RequiredType = Context.getPointerType(RequiredType);
12952
12953 bool mismatch = false;
12954 if (!TypeInfo.LayoutCompatible) {
12955 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12956
12957 // C++11 [basic.fundamental] p1:
12958 // Plain char, signed char, and unsigned char are three distinct types.
12959 //
12960 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12961 // char' depending on the current char signedness mode.
12962 if (mismatch)
12963 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12964 RequiredType->getPointeeType())) ||
12965 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12966 mismatch = false;
12967 } else
12968 if (IsPointerAttr)
12969 mismatch = !isLayoutCompatible(Context,
12970 ArgumentType->getPointeeType(),
12971 RequiredType->getPointeeType());
12972 else
12973 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12974
12975 if (mismatch)
12976 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012977 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012978 << TypeInfo.LayoutCompatible << RequiredType
12979 << ArgumentExpr->getSourceRange()
12980 << TypeTagExpr->getSourceRange();
12981}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012982
12983void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12984 CharUnits Alignment) {
12985 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12986}
12987
12988void Sema::DiagnoseMisalignedMembers() {
12989 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012990 const NamedDecl *ND = m.RD;
12991 if (ND->getName().empty()) {
12992 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12993 ND = TD;
12994 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012995 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012996 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012997 }
12998 MisalignedMembers.clear();
12999}
13000
13001void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013002 E = E->IgnoreParens();
13003 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013004 return;
13005 if (isa<UnaryOperator>(E) &&
13006 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13007 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13008 if (isa<MemberExpr>(Op)) {
13009 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13010 MisalignedMember(Op));
13011 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013012 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000013013 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13014 Context.getTypeAlignInChars(
13015 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013016 MisalignedMembers.erase(MA);
13017 }
13018 }
13019}
13020
13021void Sema::RefersToMemberWithReducedAlignment(
13022 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000013023 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13024 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013025 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013026 if (!ME)
13027 return;
13028
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000013029 // No need to check expressions with an __unaligned-qualified type.
13030 if (E->getType().getQualifiers().hasUnaligned())
13031 return;
13032
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013033 // For a chain of MemberExpr like "a.b.c.d" this list
13034 // will keep FieldDecl's like [d, c, b].
13035 SmallVector<FieldDecl *, 4> ReverseMemberChain;
13036 const MemberExpr *TopME = nullptr;
13037 bool AnyIsPacked = false;
13038 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013039 QualType BaseType = ME->getBase()->getType();
13040 if (ME->isArrow())
13041 BaseType = BaseType->getPointeeType();
13042 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000013043 if (RD->isInvalidDecl())
13044 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013045
13046 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013047 auto *FD = dyn_cast<FieldDecl>(MD);
13048 // We do not care about non-data members.
13049 if (!FD || FD->isInvalidDecl())
13050 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013051
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013052 AnyIsPacked =
13053 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13054 ReverseMemberChain.push_back(FD);
13055
13056 TopME = ME;
13057 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13058 } while (ME);
13059 assert(TopME && "We did not compute a topmost MemberExpr!");
13060
13061 // Not the scope of this diagnostic.
13062 if (!AnyIsPacked)
13063 return;
13064
13065 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13066 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13067 // TODO: The innermost base of the member expression may be too complicated.
13068 // For now, just disregard these cases. This is left for future
13069 // improvement.
13070 if (!DRE && !isa<CXXThisExpr>(TopBase))
13071 return;
13072
13073 // Alignment expected by the whole expression.
13074 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13075
13076 // No need to do anything else with this case.
13077 if (ExpectedAlignment.isOne())
13078 return;
13079
13080 // Synthesize offset of the whole access.
13081 CharUnits Offset;
13082 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13083 I++) {
13084 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13085 }
13086
13087 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13088 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13089 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13090
13091 // The base expression of the innermost MemberExpr may give
13092 // stronger guarantees than the class containing the member.
13093 if (DRE && !TopME->isArrow()) {
13094 const ValueDecl *VD = DRE->getDecl();
13095 if (!VD->getType()->isReferenceType())
13096 CompleteObjectAlignment =
13097 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13098 }
13099
13100 // Check if the synthesized offset fulfills the alignment.
13101 if (Offset % ExpectedAlignment != 0 ||
13102 // It may fulfill the offset it but the effective alignment may still be
13103 // lower than the expected expression alignment.
13104 CompleteObjectAlignment < ExpectedAlignment) {
13105 // If this happens, we want to determine a sensible culprit of this.
13106 // Intuitively, watching the chain of member expressions from right to
13107 // left, we start with the required alignment (as required by the field
13108 // type) but some packed attribute in that chain has reduced the alignment.
13109 // It may happen that another packed structure increases it again. But if
13110 // we are here such increase has not been enough. So pointing the first
13111 // FieldDecl that either is packed or else its RecordDecl is,
13112 // seems reasonable.
13113 FieldDecl *FD = nullptr;
13114 CharUnits Alignment;
13115 for (FieldDecl *FDI : ReverseMemberChain) {
13116 if (FDI->hasAttr<PackedAttr>() ||
13117 FDI->getParent()->hasAttr<PackedAttr>()) {
13118 FD = FDI;
13119 Alignment = std::min(
13120 Context.getTypeAlignInChars(FD->getType()),
13121 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13122 break;
13123 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013124 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013125 assert(FD && "We did not find a packed FieldDecl!");
13126 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013127 }
13128}
13129
13130void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13131 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013132
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013133 RefersToMemberWithReducedAlignment(
13134 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13135 _2, _3, _4));
13136}