blob: c43f656c2f42859cd80af47549e6adb2c8e8c9c4 [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerb87b1b32007-08-10 20:18:51 +00006//
7//===----------------------------------------------------------------------===//
8//
Mike Stump11289f42009-09-09 15:08:12 +00009// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000010// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000016#include "clang/AST/Attr.h"
17#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000018#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000019#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000023#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000025#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000026#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000027#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000028#include "clang/AST/ExprOpenMP.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000029#include "clang/AST/FormatString.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"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000038#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000039#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000040#include "clang/Basic/Diagnostic.h"
41#include "clang/Basic/IdentifierTable.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/LangOptions.h"
44#include "clang/Basic/OpenCLOptions.h"
45#include "clang/Basic/OperatorKinds.h"
46#include "clang/Basic/PartialDiagnostic.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000050#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000051#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000052#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000053#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000054#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000055#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000056#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000058#include "clang/Sema/Ownership.h"
59#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000060#include "clang/Sema/ScopeInfo.h"
61#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000062#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000063#include "llvm/ADT/APFloat.h"
64#include "llvm/ADT/APInt.h"
65#include "llvm/ADT/APSInt.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/DenseMap.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000071#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000072#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000073#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000074#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000075#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/StringRef.h"
77#include "llvm/ADT/StringSwitch.h"
78#include "llvm/ADT/Triple.h"
79#include "llvm/Support/AtomicOrdering.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000082#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000083#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000084#include "llvm/Support/Format.h"
85#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000086#include "llvm/Support/MathExtras.h"
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000087#include "llvm/Support/SaveAndRestore.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)
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116 << 0 /*function call*/ << desiredArgCount << argCount
117 << call->getSourceRange();
John McCallbebede42011-02-26 05:39:39 +0000118
119 // Highlight all the excess arguments.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000121 call->getArg(argCount - 1)->getEndLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000138 S.Diag(ValArg->getBeginLoc(), 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148 << StrArg->getSourceRange();
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000149 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) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
Reid Kleckner30701ed2017-09-05 20:27:35 +0000160 << 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()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
Reid Kleckner30701ed2017-09-05 20:27:35 +0000170 << 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));
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000186 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
Yonghong Song048493f2019-07-09 04:21:50 +0000194/// Check the number of arguments, and set the result type to
195/// the argument type.
196static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197 if (checkArgCount(S, TheCall, 1))
198 return true;
199
200 TheCall->setType(TheCall->getArg(0)->getType());
201 return false;
202}
203
John McCall03107a42015-10-29 20:48:01 +0000204static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
205 if (checkArgCount(S, TheCall, 3))
206 return true;
207
208 // First two arguments should be integers.
209 for (unsigned I = 0; I < 2; ++I) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000210 ExprResult Arg = TheCall->getArg(I);
211 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000212 if (!Ty->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000213 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
Erich Keane1d73d1a2018-06-13 13:25:11 +0000214 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000215 return true;
216 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000217 InitializedEntity Entity = InitializedEntity::InitializeParameter(
218 S.getASTContext(), Ty, /*consume*/ false);
219 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
220 if (Arg.isInvalid())
221 return true;
222 TheCall->setArg(I, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000223 }
224
225 // Third argument should be a pointer to a non-const integer.
226 // IRGen correctly handles volatile, restrict, and address spaces, and
227 // the other qualifiers aren't possible.
228 {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000229 ExprResult Arg = TheCall->getArg(2);
230 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000231 const auto *PtrTy = Ty->getAs<PointerType>();
232 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
233 !PtrTy->getPointeeType().isConstQualified())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000234 S.Diag(Arg.get()->getBeginLoc(),
Erich Keane1d73d1a2018-06-13 13:25:11 +0000235 diag::err_overflow_builtin_must_be_ptr_int)
236 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000237 return true;
238 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000239 InitializedEntity Entity = InitializedEntity::InitializeParameter(
240 S.getASTContext(), Ty, /*consume*/ false);
241 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
242 if (Arg.isInvalid())
243 return true;
244 TheCall->setArg(2, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000245 }
John McCall03107a42015-10-29 20:48:01 +0000246 return false;
247}
248
Peter Collingbournef7706832014-12-12 23:41:25 +0000249static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
250 if (checkArgCount(S, BuiltinCall, 2))
251 return true;
252
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000253 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
Peter Collingbournef7706832014-12-12 23:41:25 +0000254 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
255 Expr *Call = BuiltinCall->getArg(0);
256 Expr *Chain = BuiltinCall->getArg(1);
257
258 if (Call->getStmtClass() != Stmt::CallExprClass) {
259 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
260 << Call->getSourceRange();
261 return true;
262 }
263
264 auto CE = cast<CallExpr>(Call);
265 if (CE->getCallee()->getType()->isBlockPointerType()) {
266 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
267 << Call->getSourceRange();
268 return true;
269 }
270
271 const Decl *TargetDecl = CE->getCalleeDecl();
272 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
273 if (FD->getBuiltinID()) {
274 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
275 << Call->getSourceRange();
276 return true;
277 }
278
279 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
280 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
281 << Call->getSourceRange();
282 return true;
283 }
284
285 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
286 if (ChainResult.isInvalid())
287 return true;
288 if (!ChainResult.get()->getType()->isPointerType()) {
289 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
290 << Chain->getSourceRange();
291 return true;
292 }
293
David Majnemerced8bdf2015-02-25 17:36:15 +0000294 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000295 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
296 QualType BuiltinTy = S.Context.getFunctionType(
297 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
298 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
299
300 Builtin =
301 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
302
303 BuiltinCall->setType(CE->getType());
304 BuiltinCall->setValueKind(CE->getValueKind());
305 BuiltinCall->setObjectKind(CE->getObjectKind());
306 BuiltinCall->setCallee(Builtin);
307 BuiltinCall->setArg(1, ChainResult.get());
308
309 return false;
310}
311
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +0000312/// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
313/// __builtin_*_chk function, then use the object size argument specified in the
314/// source. Otherwise, infer the object size using __builtin_object_size.
315void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
316 CallExpr *TheCall) {
317 // FIXME: There are some more useful checks we could be doing here:
318 // - Analyze the format string of sprintf to see how much of buffer is used.
319 // - Evaluate strlen of strcpy arguments, use as object size.
320
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +0000321 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
322 isConstantEvaluated())
Erik Pilkington233ff942019-03-29 19:53:41 +0000323 return;
324
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +0000325 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
326 if (!BuiltinID)
327 return;
328
329 unsigned DiagID = 0;
330 bool IsChkVariant = false;
331 unsigned SizeIndex, ObjectIndex;
332 switch (BuiltinID) {
333 default:
334 return;
335 case Builtin::BI__builtin___memcpy_chk:
336 case Builtin::BI__builtin___memmove_chk:
337 case Builtin::BI__builtin___memset_chk:
338 case Builtin::BI__builtin___strlcat_chk:
339 case Builtin::BI__builtin___strlcpy_chk:
340 case Builtin::BI__builtin___strncat_chk:
341 case Builtin::BI__builtin___strncpy_chk:
342 case Builtin::BI__builtin___stpncpy_chk:
343 case Builtin::BI__builtin___memccpy_chk: {
344 DiagID = diag::warn_builtin_chk_overflow;
345 IsChkVariant = true;
346 SizeIndex = TheCall->getNumArgs() - 2;
347 ObjectIndex = TheCall->getNumArgs() - 1;
348 break;
349 }
350
351 case Builtin::BI__builtin___snprintf_chk:
352 case Builtin::BI__builtin___vsnprintf_chk: {
353 DiagID = diag::warn_builtin_chk_overflow;
354 IsChkVariant = true;
355 SizeIndex = 1;
356 ObjectIndex = 3;
357 break;
358 }
359
360 case Builtin::BIstrncat:
361 case Builtin::BI__builtin_strncat:
362 case Builtin::BIstrncpy:
363 case Builtin::BI__builtin_strncpy:
364 case Builtin::BIstpncpy:
365 case Builtin::BI__builtin_stpncpy: {
366 // Whether these functions overflow depends on the runtime strlen of the
367 // string, not just the buffer size, so emitting the "always overflow"
368 // diagnostic isn't quite right. We should still diagnose passing a buffer
369 // size larger than the destination buffer though; this is a runtime abort
370 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
371 DiagID = diag::warn_fortify_source_size_mismatch;
372 SizeIndex = TheCall->getNumArgs() - 1;
373 ObjectIndex = 0;
374 break;
375 }
376
377 case Builtin::BImemcpy:
378 case Builtin::BI__builtin_memcpy:
379 case Builtin::BImemmove:
380 case Builtin::BI__builtin_memmove:
381 case Builtin::BImemset:
382 case Builtin::BI__builtin_memset: {
383 DiagID = diag::warn_fortify_source_overflow;
384 SizeIndex = TheCall->getNumArgs() - 1;
385 ObjectIndex = 0;
386 break;
387 }
388 case Builtin::BIsnprintf:
389 case Builtin::BI__builtin_snprintf:
390 case Builtin::BIvsnprintf:
391 case Builtin::BI__builtin_vsnprintf: {
392 DiagID = diag::warn_fortify_source_size_mismatch;
393 SizeIndex = 1;
394 ObjectIndex = 0;
395 break;
396 }
397 }
398
399 llvm::APSInt ObjectSize;
400 // For __builtin___*_chk, the object size is explicitly provided by the caller
401 // (usually using __builtin_object_size). Use that value to check this call.
402 if (IsChkVariant) {
403 Expr::EvalResult Result;
404 Expr *SizeArg = TheCall->getArg(ObjectIndex);
405 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
406 return;
407 ObjectSize = Result.Val.getInt();
408
409 // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
410 } else {
411 // If the parameter has a pass_object_size attribute, then we should use its
412 // (potentially) more strict checking mode. Otherwise, conservatively assume
413 // type 0.
414 int BOSType = 0;
415 if (const auto *POS =
416 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
417 BOSType = POS->getType();
418
419 Expr *ObjArg = TheCall->getArg(ObjectIndex);
420 uint64_t Result;
421 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
422 return;
423 // Get the object size in the target's size_t width.
424 const TargetInfo &TI = getASTContext().getTargetInfo();
425 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
426 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
427 }
428
429 // Evaluate the number of bytes of the object that this call will use.
430 Expr::EvalResult Result;
431 Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
432 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
433 return;
434 llvm::APSInt UsedSize = Result.Val.getInt();
435
436 if (UsedSize.ule(ObjectSize))
437 return;
438
439 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
440 // Skim off the details of whichever builtin was called to produce a better
441 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
442 if (IsChkVariant) {
443 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
444 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
445 } else if (FunctionName.startswith("__builtin_")) {
446 FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
447 }
448
Erik Pilkington81869802019-03-26 23:21:22 +0000449 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
450 PDiag(DiagID)
451 << FunctionName << ObjectSize.toString(/*Radix=*/10)
452 << UsedSize.toString(/*Radix=*/10));
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +0000453}
454
Reid Kleckner1d59f992015-01-22 01:36:17 +0000455static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
456 Scope::ScopeFlags NeededScopeFlags,
457 unsigned DiagID) {
458 // Scopes aren't available during instantiation. Fortunately, builtin
459 // functions cannot be template args so they cannot be formed through template
460 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000461 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000462 return false;
463
464 Scope *S = SemaRef.getCurScope();
465 while (S && !S->isSEHExceptScope())
466 S = S->getParent();
467 if (!S || !(S->getFlags() & NeededScopeFlags)) {
468 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
469 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
470 << DRE->getDecl()->getIdentifier();
471 return true;
472 }
473
474 return false;
475}
476
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000477static inline bool isBlockPointer(Expr *Arg) {
478 return Arg->getType()->isBlockPointerType();
479}
480
481/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
482/// void*, which is a requirement of device side enqueue.
483static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
484 const BlockPointerType *BPT =
485 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
486 ArrayRef<QualType> Params =
487 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
488 unsigned ArgCounter = 0;
489 bool IllegalParams = false;
490 // Iterate through the block parameters until either one is found that is not
491 // a local void*, or the block is valid.
492 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
493 I != E; ++I, ++ArgCounter) {
494 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
495 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
496 LangAS::opencl_local) {
497 // Get the location of the error. If a block literal has been passed
498 // (BlockExpr) then we can point straight to the offending argument,
499 // else we just point to the variable reference.
500 SourceLocation ErrorLoc;
501 if (isa<BlockExpr>(BlockArg)) {
502 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000503 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000504 } else if (isa<DeclRefExpr>(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000505 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000506 }
507 S.Diag(ErrorLoc,
508 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
509 IllegalParams = true;
510 }
511 }
512
513 return IllegalParams;
514}
515
Joey Gouly84ae3362017-07-31 15:15:59 +0000516static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
517 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000518 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
519 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
Joey Gouly84ae3362017-07-31 15:15:59 +0000520 return true;
521 }
522 return false;
523}
524
Joey Goulyfa76b492017-08-01 13:27:09 +0000525static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
526 if (checkArgCount(S, TheCall, 2))
527 return true;
528
529 if (checkOpenCLSubgroupExt(S, TheCall))
530 return true;
531
532 // First argument is an ndrange_t type.
533 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000534 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000535 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000536 << TheCall->getDirectCallee() << "'ndrange_t'";
537 return true;
538 }
539
540 Expr *BlockArg = TheCall->getArg(1);
541 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000542 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000543 << TheCall->getDirectCallee() << "block";
544 return true;
545 }
546 return checkOpenCLBlockArgs(S, BlockArg);
547}
548
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000549/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
550/// get_kernel_work_group_size
551/// and get_kernel_preferred_work_group_size_multiple builtin functions.
552static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
553 if (checkArgCount(S, TheCall, 1))
554 return true;
555
556 Expr *BlockArg = TheCall->getArg(0);
557 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000558 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000559 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000560 return true;
561 }
562 return checkOpenCLBlockArgs(S, BlockArg);
563}
564
Simon Pilgrim2c518802017-03-30 14:13:19 +0000565/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000566static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
567 const QualType &IntType);
568
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000569static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000570 unsigned Start, unsigned End) {
571 bool IllegalParams = false;
572 for (unsigned I = Start; I <= End; ++I)
573 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
574 S.Context.getSizeType());
575 return IllegalParams;
576}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000577
578/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
579/// 'local void*' parameter of passed block.
580static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
581 Expr *BlockArg,
582 unsigned NumNonVarArgs) {
583 const BlockPointerType *BPT =
584 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
585 unsigned NumBlockParams =
586 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
587 unsigned TotalNumArgs = TheCall->getNumArgs();
588
589 // For each argument passed to the block, a corresponding uint needs to
590 // be passed to describe the size of the local memory.
591 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000592 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000593 diag::err_opencl_enqueue_kernel_local_size_args);
594 return true;
595 }
596
597 // Check that the sizes of the local memory are specified by integers.
598 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
599 TotalNumArgs - 1);
600}
601
602/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
603/// overload formats specified in Table 6.13.17.1.
604/// int enqueue_kernel(queue_t queue,
605/// kernel_enqueue_flags_t flags,
606/// const ndrange_t ndrange,
607/// void (^block)(void))
608/// int enqueue_kernel(queue_t queue,
609/// kernel_enqueue_flags_t flags,
610/// const ndrange_t ndrange,
611/// uint num_events_in_wait_list,
612/// clk_event_t *event_wait_list,
613/// clk_event_t *event_ret,
614/// void (^block)(void))
615/// int enqueue_kernel(queue_t queue,
616/// kernel_enqueue_flags_t flags,
617/// const ndrange_t ndrange,
618/// void (^block)(local void*, ...),
619/// uint size0, ...)
620/// int enqueue_kernel(queue_t queue,
621/// kernel_enqueue_flags_t flags,
622/// const ndrange_t ndrange,
623/// uint num_events_in_wait_list,
624/// clk_event_t *event_wait_list,
625/// clk_event_t *event_ret,
626/// void (^block)(local void*, ...),
627/// uint size0, ...)
628static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
629 unsigned NumArgs = TheCall->getNumArgs();
630
631 if (NumArgs < 4) {
Sven van Haastregta280b632019-08-29 10:21:06 +0000632 S.Diag(TheCall->getBeginLoc(),
633 diag::err_typecheck_call_too_few_args_at_least)
634 << 0 << 4 << NumArgs;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000635 return true;
636 }
637
638 Expr *Arg0 = TheCall->getArg(0);
639 Expr *Arg1 = TheCall->getArg(1);
640 Expr *Arg2 = TheCall->getArg(2);
641 Expr *Arg3 = TheCall->getArg(3);
642
643 // First argument always needs to be a queue_t type.
644 if (!Arg0->getType()->isQueueT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000645 S.Diag(TheCall->getArg(0)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000646 diag::err_opencl_builtin_expected_type)
647 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000648 return true;
649 }
650
651 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
652 if (!Arg1->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000653 S.Diag(TheCall->getArg(1)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000654 diag::err_opencl_builtin_expected_type)
655 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000656 return true;
657 }
658
659 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000660 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000661 S.Diag(TheCall->getArg(2)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000662 diag::err_opencl_builtin_expected_type)
663 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000664 return true;
665 }
666
667 // With four arguments, there is only one form that the function could be
668 // called in: no events and no variable arguments.
669 if (NumArgs == 4) {
670 // check that the last argument is the right block type.
671 if (!isBlockPointer(Arg3)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000672 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000673 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000674 return true;
675 }
676 // we have a block type, check the prototype
677 const BlockPointerType *BPT =
678 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
679 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000680 S.Diag(Arg3->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000681 diag::err_opencl_enqueue_kernel_blocks_no_args);
682 return true;
683 }
684 return false;
685 }
686 // we can have block + varargs.
687 if (isBlockPointer(Arg3))
688 return (checkOpenCLBlockArgs(S, Arg3) ||
689 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
690 // last two cases with either exactly 7 args or 7 args and varargs.
691 if (NumArgs >= 7) {
692 // check common block argument.
693 Expr *Arg6 = TheCall->getArg(6);
694 if (!isBlockPointer(Arg6)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000695 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000696 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000697 return true;
698 }
699 if (checkOpenCLBlockArgs(S, Arg6))
700 return true;
701
702 // Forth argument has to be any integer type.
703 if (!Arg3->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000704 S.Diag(TheCall->getArg(3)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000705 diag::err_opencl_builtin_expected_type)
706 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000707 return true;
708 }
709 // check remaining common arguments.
710 Expr *Arg4 = TheCall->getArg(4);
711 Expr *Arg5 = TheCall->getArg(5);
712
Anastasia Stulova2b461202016-11-14 15:34:01 +0000713 // Fifth argument is always passed as a pointer to clk_event_t.
714 if (!Arg4->isNullPointerConstant(S.Context,
715 Expr::NPC_ValueDependentIsNotNull) &&
716 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000717 S.Diag(TheCall->getArg(4)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000718 diag::err_opencl_builtin_expected_type)
719 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000720 << S.Context.getPointerType(S.Context.OCLClkEventTy);
721 return true;
722 }
723
Anastasia Stulova2b461202016-11-14 15:34:01 +0000724 // Sixth argument is always passed as a pointer to clk_event_t.
725 if (!Arg5->isNullPointerConstant(S.Context,
726 Expr::NPC_ValueDependentIsNotNull) &&
727 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000728 Arg5->getType()->getPointeeType()->isClkEventT())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000729 S.Diag(TheCall->getArg(5)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000730 diag::err_opencl_builtin_expected_type)
731 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000732 << S.Context.getPointerType(S.Context.OCLClkEventTy);
733 return true;
734 }
735
736 if (NumArgs == 7)
737 return false;
738
739 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
740 }
741
742 // None of the specific case has been detected, give generic error
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000743 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000744 diag::err_opencl_enqueue_kernel_incorrect_args);
745 return true;
746}
747
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000748/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000749static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000750 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000751}
752
753/// Returns true if pipe element type is different from the pointer.
754static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
755 const Expr *Arg0 = Call->getArg(0);
756 // First argument type should always be pipe.
757 if (!Arg0->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000758 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000759 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000760 return true;
761 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000762 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000763 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
764 // Validates the access qualifier is compatible with the call.
765 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
766 // read_only and write_only, and assumed to be read_only if no qualifier is
767 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000768 switch (Call->getDirectCallee()->getBuiltinID()) {
769 case Builtin::BIread_pipe:
770 case Builtin::BIreserve_read_pipe:
771 case Builtin::BIcommit_read_pipe:
772 case Builtin::BIwork_group_reserve_read_pipe:
773 case Builtin::BIsub_group_reserve_read_pipe:
774 case Builtin::BIwork_group_commit_read_pipe:
775 case Builtin::BIsub_group_commit_read_pipe:
776 if (!(!AccessQual || AccessQual->isReadOnly())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000777 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000778 diag::err_opencl_builtin_pipe_invalid_access_modifier)
779 << "read_only" << Arg0->getSourceRange();
780 return true;
781 }
782 break;
783 case Builtin::BIwrite_pipe:
784 case Builtin::BIreserve_write_pipe:
785 case Builtin::BIcommit_write_pipe:
786 case Builtin::BIwork_group_reserve_write_pipe:
787 case Builtin::BIsub_group_reserve_write_pipe:
788 case Builtin::BIwork_group_commit_write_pipe:
789 case Builtin::BIsub_group_commit_write_pipe:
790 if (!(AccessQual && AccessQual->isWriteOnly())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000791 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000792 diag::err_opencl_builtin_pipe_invalid_access_modifier)
793 << "write_only" << Arg0->getSourceRange();
794 return true;
795 }
796 break;
797 default:
798 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000799 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000800 return false;
801}
802
803/// Returns true if pipe element type is different from the pointer.
804static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
805 const Expr *Arg0 = Call->getArg(0);
806 const Expr *ArgIdx = Call->getArg(Idx);
807 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000808 const QualType EltTy = PipeTy->getElementType();
809 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000810 // The Idx argument should be a pointer and the type of the pointer and
811 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000812 if (!ArgTy ||
813 !S.Context.hasSameType(
814 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000815 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000816 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000817 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000818 return true;
819 }
820 return false;
821}
822
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000823// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000824// \param S Reference to the semantic analyzer.
825// \param Call A pointer to the builtin call.
826// \return True if a semantic error has been found, false otherwise.
827static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000828 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
829 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000830 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000831 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000832 if (checkOpenCLPipeArg(S, Call))
833 return true;
834 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000835 // read/write_pipe(pipe T, T*).
836 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000837 if (checkOpenCLPipePacketType(S, Call, 1))
838 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000839 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000840
841 case 4: {
842 if (checkOpenCLPipeArg(S, Call))
843 return true;
844 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000845 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
846 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000847 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000848 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000849 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000850 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000851 return true;
852 }
853
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000854 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000855 const Expr *Arg2 = Call->getArg(2);
856 if (!Arg2->getType()->isIntegerType() &&
857 !Arg2->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000858 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000859 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000860 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000861 return true;
862 }
863
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000864 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000865 if (checkOpenCLPipePacketType(S, Call, 3))
866 return true;
867 } break;
868 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000869 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000870 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000871 return true;
872 }
873
874 return false;
875}
876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000877// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000878// /_}reserve_{read/write}_pipe
879// \param S Reference to the semantic analyzer.
880// \param Call The call to the builtin function to be analyzed.
881// \return True if a semantic error was found, false otherwise.
882static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
883 if (checkArgCount(S, Call, 2))
884 return true;
885
886 if (checkOpenCLPipeArg(S, Call))
887 return true;
888
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000889 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000890 if (!Call->getArg(1)->getType()->isIntegerType() &&
891 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000892 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000893 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000894 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000895 return true;
896 }
897
Joey Gouly922ca232017-08-09 14:52:47 +0000898 // Since return type of reserve_read/write_pipe built-in function is
Aaron Ballman68d50642018-06-19 14:53:20 +0000899 // reserve_id_t, which is not defined in the builtin def file , we used int
900 // as return type and need to override the return type of these functions.
901 Call->setType(S.Context.OCLReserveIDTy);
902
903 return false;
904}
905
906// Performs a semantic analysis on {work_group_/sub_group_
907// /_}commit_{read/write}_pipe
908// \param S Reference to the semantic analyzer.
909// \param Call The call to the builtin function to be analyzed.
910// \return True if a semantic error was found, false otherwise.
911static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
912 if (checkArgCount(S, Call, 2))
913 return true;
914
915 if (checkOpenCLPipeArg(S, Call))
916 return true;
917
918 // Check reserve_id_t.
919 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000920 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000921 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
922 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
923 return true;
924 }
925
926 return false;
927}
928
929// Performs a semantic analysis on the call to built-in Pipe
930// Query Functions.
931// \param S Reference to the semantic analyzer.
932// \param Call The call to the builtin function to be analyzed.
933// \return True if a semantic error was found, false otherwise.
934static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
935 if (checkArgCount(S, Call, 1))
936 return true;
937
938 if (!Call->getArg(0)->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000939 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000940 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
941 return true;
942 }
943
944 return false;
945}
946
947// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
948// Performs semantic analysis for the to_global/local/private call.
949// \param S Reference to the semantic analyzer.
950// \param BuiltinID ID of the builtin function.
951// \param Call A pointer to the builtin call.
952// \return True if a semantic error has been found, false otherwise.
953static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
954 CallExpr *Call) {
955 if (Call->getNumArgs() != 1) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000956 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
Aaron Ballman68d50642018-06-19 14:53:20 +0000957 << Call->getDirectCallee() << Call->getSourceRange();
958 return true;
959 }
960
961 auto RT = Call->getArg(0)->getType();
962 if (!RT->isPointerType() || RT->getPointeeType()
963 .getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000964 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000965 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
966 return true;
967 }
968
Sven van Haastregt1076cc22018-09-20 10:07:27 +0000969 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
970 S.Diag(Call->getArg(0)->getBeginLoc(),
971 diag::warn_opencl_generic_address_space_arg)
972 << Call->getDirectCallee()->getNameInfo().getAsString()
973 << Call->getArg(0)->getSourceRange();
974 }
975
Aaron Ballman68d50642018-06-19 14:53:20 +0000976 RT = RT->getPointeeType();
977 auto Qual = RT.getQualifiers();
978 switch (BuiltinID) {
979 case Builtin::BIto_global:
980 Qual.setAddressSpace(LangAS::opencl_global);
981 break;
982 case Builtin::BIto_local:
983 Qual.setAddressSpace(LangAS::opencl_local);
984 break;
985 case Builtin::BIto_private:
986 Qual.setAddressSpace(LangAS::opencl_private);
987 break;
988 default:
989 llvm_unreachable("Invalid builtin function");
990 }
991 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
992 RT.getUnqualifiedType(), Qual)));
993
994 return false;
995}
996
Eric Fiselier26187502018-12-14 21:11:28 +0000997static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
998 if (checkArgCount(S, TheCall, 1))
999 return ExprError();
1000
1001 // Compute __builtin_launder's parameter type from the argument.
1002 // The parameter type is:
1003 // * The type of the argument if it's not an array or function type,
1004 // Otherwise,
1005 // * The decayed argument type.
1006 QualType ParamTy = [&]() {
1007 QualType ArgTy = TheCall->getArg(0)->getType();
1008 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1009 return S.Context.getPointerType(Ty->getElementType());
1010 if (ArgTy->isFunctionType()) {
1011 return S.Context.getPointerType(ArgTy);
1012 }
1013 return ArgTy;
1014 }();
1015
1016 TheCall->setType(ParamTy);
1017
1018 auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1019 if (!ParamTy->isPointerType())
1020 return 0;
1021 if (ParamTy->isFunctionPointerType())
1022 return 1;
1023 if (ParamTy->isVoidPointerType())
1024 return 2;
1025 return llvm::Optional<unsigned>{};
1026 }();
1027 if (DiagSelect.hasValue()) {
1028 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1029 << DiagSelect.getValue() << TheCall->getSourceRange();
1030 return ExprError();
1031 }
1032
1033 // We either have an incomplete class type, or we have a class template
1034 // whose instantiation has not been forced. Example:
1035 //
1036 // template <class T> struct Foo { T value; };
1037 // Foo<int> *p = nullptr;
1038 // auto *d = __builtin_launder(p);
1039 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1040 diag::err_incomplete_type))
1041 return ExprError();
1042
1043 assert(ParamTy->getPointeeType()->isObjectType() &&
1044 "Unhandled non-object pointer case");
1045
1046 InitializedEntity Entity =
1047 InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1048 ExprResult Arg =
1049 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1050 if (Arg.isInvalid())
1051 return ExprError();
1052 TheCall->setArg(0, Arg.get());
1053
1054 return TheCall;
1055}
1056
Aaron Ballman68d50642018-06-19 14:53:20 +00001057// Emit an error and return true if the current architecture is not in the list
1058// of supported architectures.
1059static bool
1060CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1061 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1062 llvm::Triple::ArchType CurArch =
1063 S.getASTContext().getTargetInfo().getTriple().getArch();
1064 if (llvm::is_contained(SupportedArchs, CurArch))
1065 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001066 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
Aaron Ballman68d50642018-06-19 14:53:20 +00001067 << TheCall->getSourceRange();
1068 return true;
1069}
1070
1071ExprResult
1072Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1073 CallExpr *TheCall) {
1074 ExprResult TheCallResult(TheCall);
1075
1076 // Find out if any arguments are required to be integer constant expressions.
1077 unsigned ICEArguments = 0;
1078 ASTContext::GetBuiltinTypeError Error;
1079 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1080 if (Error != ASTContext::GE_None)
1081 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
Fangrui Song6907ce22018-07-30 19:24:48 +00001082
Aaron Ballman68d50642018-06-19 14:53:20 +00001083 // If any arguments are required to be ICE's, check and diagnose.
1084 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1085 // Skip arguments not required to be ICE's.
1086 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001087
Aaron Ballman68d50642018-06-19 14:53:20 +00001088 llvm::APSInt Result;
1089 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1090 return true;
1091 ICEArguments &= ~(1 << ArgNo);
1092 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001093
Aaron Ballman68d50642018-06-19 14:53:20 +00001094 switch (BuiltinID) {
1095 case Builtin::BI__builtin___CFStringMakeConstantString:
1096 assert(TheCall->getNumArgs() == 1 &&
1097 "Wrong # arguments to builtin CFStringMakeConstantString");
1098 if (CheckObjCString(TheCall->getArg(0)))
1099 return ExprError();
1100 break;
1101 case Builtin::BI__builtin_ms_va_start:
1102 case Builtin::BI__builtin_stdarg_start:
1103 case Builtin::BI__builtin_va_start:
1104 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1105 return ExprError();
1106 break;
1107 case Builtin::BI__va_start: {
1108 switch (Context.getTargetInfo().getTriple().getArch()) {
Martin Storsjo0b339e42018-09-27 08:24:15 +00001109 case llvm::Triple::aarch64:
Aaron Ballman68d50642018-06-19 14:53:20 +00001110 case llvm::Triple::arm:
1111 case llvm::Triple::thumb:
1112 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1113 return ExprError();
1114 break;
1115 default:
1116 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1117 return ExprError();
1118 break;
1119 }
1120 break;
1121 }
1122
1123 // The acquire, release, and no fence variants are ARM and AArch64 only.
1124 case Builtin::BI_interlockedbittestandset_acq:
1125 case Builtin::BI_interlockedbittestandset_rel:
1126 case Builtin::BI_interlockedbittestandset_nf:
1127 case Builtin::BI_interlockedbittestandreset_acq:
1128 case Builtin::BI_interlockedbittestandreset_rel:
1129 case Builtin::BI_interlockedbittestandreset_nf:
1130 if (CheckBuiltinTargetSupport(
1131 *this, BuiltinID, TheCall,
1132 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1133 return ExprError();
1134 break;
1135
1136 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1137 case Builtin::BI_bittest64:
1138 case Builtin::BI_bittestandcomplement64:
1139 case Builtin::BI_bittestandreset64:
1140 case Builtin::BI_bittestandset64:
1141 case Builtin::BI_interlockedbittestandreset64:
1142 case Builtin::BI_interlockedbittestandset64:
1143 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1144 {llvm::Triple::x86_64, llvm::Triple::arm,
1145 llvm::Triple::thumb, llvm::Triple::aarch64}))
1146 return ExprError();
1147 break;
1148
1149 case Builtin::BI__builtin_isgreater:
1150 case Builtin::BI__builtin_isgreaterequal:
1151 case Builtin::BI__builtin_isless:
1152 case Builtin::BI__builtin_islessequal:
1153 case Builtin::BI__builtin_islessgreater:
1154 case Builtin::BI__builtin_isunordered:
1155 if (SemaBuiltinUnorderedCompare(TheCall))
1156 return ExprError();
1157 break;
1158 case Builtin::BI__builtin_fpclassify:
1159 if (SemaBuiltinFPClassification(TheCall, 6))
1160 return ExprError();
1161 break;
1162 case Builtin::BI__builtin_isfinite:
1163 case Builtin::BI__builtin_isinf:
1164 case Builtin::BI__builtin_isinf_sign:
1165 case Builtin::BI__builtin_isnan:
1166 case Builtin::BI__builtin_isnormal:
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00001167 case Builtin::BI__builtin_signbit:
1168 case Builtin::BI__builtin_signbitf:
1169 case Builtin::BI__builtin_signbitl:
Aaron Ballman68d50642018-06-19 14:53:20 +00001170 if (SemaBuiltinFPClassification(TheCall, 1))
1171 return ExprError();
1172 break;
1173 case Builtin::BI__builtin_shufflevector:
1174 return SemaBuiltinShuffleVector(TheCall);
1175 // TheCall will be freed by the smart pointer here, but that's fine, since
1176 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1177 case Builtin::BI__builtin_prefetch:
1178 if (SemaBuiltinPrefetch(TheCall))
1179 return ExprError();
1180 break;
1181 case Builtin::BI__builtin_alloca_with_align:
1182 if (SemaBuiltinAllocaWithAlign(TheCall))
1183 return ExprError();
George Burgess IV9d045a52019-07-25 22:23:40 +00001184 LLVM_FALLTHROUGH;
1185 case Builtin::BI__builtin_alloca:
1186 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1187 << TheCall->getDirectCallee();
Aaron Ballman68d50642018-06-19 14:53:20 +00001188 break;
1189 case Builtin::BI__assume:
1190 case Builtin::BI__builtin_assume:
1191 if (SemaBuiltinAssume(TheCall))
1192 return ExprError();
1193 break;
1194 case Builtin::BI__builtin_assume_aligned:
1195 if (SemaBuiltinAssumeAligned(TheCall))
1196 return ExprError();
1197 break;
Erik Pilkington9c3b5882019-01-30 20:34:53 +00001198 case Builtin::BI__builtin_dynamic_object_size:
Aaron Ballman68d50642018-06-19 14:53:20 +00001199 case Builtin::BI__builtin_object_size:
1200 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1201 return ExprError();
1202 break;
1203 case Builtin::BI__builtin_longjmp:
1204 if (SemaBuiltinLongjmp(TheCall))
1205 return ExprError();
1206 break;
1207 case Builtin::BI__builtin_setjmp:
1208 if (SemaBuiltinSetjmp(TheCall))
1209 return ExprError();
1210 break;
1211 case Builtin::BI_setjmp:
1212 case Builtin::BI_setjmpex:
1213 if (checkArgCount(*this, TheCall, 1))
1214 return true;
1215 break;
1216 case Builtin::BI__builtin_classify_type:
1217 if (checkArgCount(*this, TheCall, 1)) return true;
1218 TheCall->setType(Context.IntTy);
1219 break;
Richard Smith31cfb312019-04-27 02:58:17 +00001220 case Builtin::BI__builtin_constant_p: {
Aaron Ballman68d50642018-06-19 14:53:20 +00001221 if (checkArgCount(*this, TheCall, 1)) return true;
Richard Smith31cfb312019-04-27 02:58:17 +00001222 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1223 if (Arg.isInvalid()) return true;
1224 TheCall->setArg(0, Arg.get());
Aaron Ballman68d50642018-06-19 14:53:20 +00001225 TheCall->setType(Context.IntTy);
1226 break;
Richard Smith31cfb312019-04-27 02:58:17 +00001227 }
Eric Fiselier26187502018-12-14 21:11:28 +00001228 case Builtin::BI__builtin_launder:
1229 return SemaBuiltinLaunder(*this, TheCall);
Aaron Ballman68d50642018-06-19 14:53:20 +00001230 case Builtin::BI__sync_fetch_and_add:
1231 case Builtin::BI__sync_fetch_and_add_1:
1232 case Builtin::BI__sync_fetch_and_add_2:
1233 case Builtin::BI__sync_fetch_and_add_4:
1234 case Builtin::BI__sync_fetch_and_add_8:
1235 case Builtin::BI__sync_fetch_and_add_16:
1236 case Builtin::BI__sync_fetch_and_sub:
1237 case Builtin::BI__sync_fetch_and_sub_1:
1238 case Builtin::BI__sync_fetch_and_sub_2:
1239 case Builtin::BI__sync_fetch_and_sub_4:
1240 case Builtin::BI__sync_fetch_and_sub_8:
1241 case Builtin::BI__sync_fetch_and_sub_16:
1242 case Builtin::BI__sync_fetch_and_or:
1243 case Builtin::BI__sync_fetch_and_or_1:
1244 case Builtin::BI__sync_fetch_and_or_2:
1245 case Builtin::BI__sync_fetch_and_or_4:
1246 case Builtin::BI__sync_fetch_and_or_8:
1247 case Builtin::BI__sync_fetch_and_or_16:
1248 case Builtin::BI__sync_fetch_and_and:
1249 case Builtin::BI__sync_fetch_and_and_1:
1250 case Builtin::BI__sync_fetch_and_and_2:
1251 case Builtin::BI__sync_fetch_and_and_4:
1252 case Builtin::BI__sync_fetch_and_and_8:
1253 case Builtin::BI__sync_fetch_and_and_16:
1254 case Builtin::BI__sync_fetch_and_xor:
1255 case Builtin::BI__sync_fetch_and_xor_1:
1256 case Builtin::BI__sync_fetch_and_xor_2:
1257 case Builtin::BI__sync_fetch_and_xor_4:
1258 case Builtin::BI__sync_fetch_and_xor_8:
1259 case Builtin::BI__sync_fetch_and_xor_16:
1260 case Builtin::BI__sync_fetch_and_nand:
1261 case Builtin::BI__sync_fetch_and_nand_1:
1262 case Builtin::BI__sync_fetch_and_nand_2:
1263 case Builtin::BI__sync_fetch_and_nand_4:
1264 case Builtin::BI__sync_fetch_and_nand_8:
1265 case Builtin::BI__sync_fetch_and_nand_16:
1266 case Builtin::BI__sync_add_and_fetch:
1267 case Builtin::BI__sync_add_and_fetch_1:
1268 case Builtin::BI__sync_add_and_fetch_2:
1269 case Builtin::BI__sync_add_and_fetch_4:
1270 case Builtin::BI__sync_add_and_fetch_8:
1271 case Builtin::BI__sync_add_and_fetch_16:
1272 case Builtin::BI__sync_sub_and_fetch:
1273 case Builtin::BI__sync_sub_and_fetch_1:
1274 case Builtin::BI__sync_sub_and_fetch_2:
1275 case Builtin::BI__sync_sub_and_fetch_4:
1276 case Builtin::BI__sync_sub_and_fetch_8:
1277 case Builtin::BI__sync_sub_and_fetch_16:
1278 case Builtin::BI__sync_and_and_fetch:
1279 case Builtin::BI__sync_and_and_fetch_1:
1280 case Builtin::BI__sync_and_and_fetch_2:
1281 case Builtin::BI__sync_and_and_fetch_4:
1282 case Builtin::BI__sync_and_and_fetch_8:
1283 case Builtin::BI__sync_and_and_fetch_16:
1284 case Builtin::BI__sync_or_and_fetch:
1285 case Builtin::BI__sync_or_and_fetch_1:
1286 case Builtin::BI__sync_or_and_fetch_2:
1287 case Builtin::BI__sync_or_and_fetch_4:
1288 case Builtin::BI__sync_or_and_fetch_8:
1289 case Builtin::BI__sync_or_and_fetch_16:
1290 case Builtin::BI__sync_xor_and_fetch:
1291 case Builtin::BI__sync_xor_and_fetch_1:
1292 case Builtin::BI__sync_xor_and_fetch_2:
1293 case Builtin::BI__sync_xor_and_fetch_4:
1294 case Builtin::BI__sync_xor_and_fetch_8:
1295 case Builtin::BI__sync_xor_and_fetch_16:
1296 case Builtin::BI__sync_nand_and_fetch:
1297 case Builtin::BI__sync_nand_and_fetch_1:
1298 case Builtin::BI__sync_nand_and_fetch_2:
1299 case Builtin::BI__sync_nand_and_fetch_4:
1300 case Builtin::BI__sync_nand_and_fetch_8:
1301 case Builtin::BI__sync_nand_and_fetch_16:
1302 case Builtin::BI__sync_val_compare_and_swap:
1303 case Builtin::BI__sync_val_compare_and_swap_1:
1304 case Builtin::BI__sync_val_compare_and_swap_2:
1305 case Builtin::BI__sync_val_compare_and_swap_4:
1306 case Builtin::BI__sync_val_compare_and_swap_8:
1307 case Builtin::BI__sync_val_compare_and_swap_16:
1308 case Builtin::BI__sync_bool_compare_and_swap:
1309 case Builtin::BI__sync_bool_compare_and_swap_1:
1310 case Builtin::BI__sync_bool_compare_and_swap_2:
1311 case Builtin::BI__sync_bool_compare_and_swap_4:
1312 case Builtin::BI__sync_bool_compare_and_swap_8:
1313 case Builtin::BI__sync_bool_compare_and_swap_16:
1314 case Builtin::BI__sync_lock_test_and_set:
1315 case Builtin::BI__sync_lock_test_and_set_1:
1316 case Builtin::BI__sync_lock_test_and_set_2:
1317 case Builtin::BI__sync_lock_test_and_set_4:
1318 case Builtin::BI__sync_lock_test_and_set_8:
1319 case Builtin::BI__sync_lock_test_and_set_16:
1320 case Builtin::BI__sync_lock_release:
1321 case Builtin::BI__sync_lock_release_1:
1322 case Builtin::BI__sync_lock_release_2:
1323 case Builtin::BI__sync_lock_release_4:
1324 case Builtin::BI__sync_lock_release_8:
1325 case Builtin::BI__sync_lock_release_16:
1326 case Builtin::BI__sync_swap:
1327 case Builtin::BI__sync_swap_1:
1328 case Builtin::BI__sync_swap_2:
1329 case Builtin::BI__sync_swap_4:
1330 case Builtin::BI__sync_swap_8:
1331 case Builtin::BI__sync_swap_16:
1332 return SemaBuiltinAtomicOverloaded(TheCallResult);
JF Bastiene77b48b2018-09-10 20:42:56 +00001333 case Builtin::BI__sync_synchronize:
1334 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1335 << TheCall->getCallee()->getSourceRange();
1336 break;
Aaron Ballman68d50642018-06-19 14:53:20 +00001337 case Builtin::BI__builtin_nontemporal_load:
1338 case Builtin::BI__builtin_nontemporal_store:
1339 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1340#define BUILTIN(ID, TYPE, ATTRS)
1341#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1342 case Builtin::BI##ID: \
1343 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1344#include "clang/Basic/Builtins.def"
1345 case Builtin::BI__annotation:
1346 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1347 return ExprError();
1348 break;
1349 case Builtin::BI__builtin_annotation:
1350 if (SemaBuiltinAnnotation(*this, TheCall))
1351 return ExprError();
1352 break;
1353 case Builtin::BI__builtin_addressof:
1354 if (SemaBuiltinAddressof(*this, TheCall))
1355 return ExprError();
1356 break;
1357 case Builtin::BI__builtin_add_overflow:
1358 case Builtin::BI__builtin_sub_overflow:
1359 case Builtin::BI__builtin_mul_overflow:
1360 if (SemaBuiltinOverflow(*this, TheCall))
1361 return ExprError();
1362 break;
1363 case Builtin::BI__builtin_operator_new:
1364 case Builtin::BI__builtin_operator_delete: {
1365 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1366 ExprResult Res =
1367 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1368 if (Res.isInvalid())
1369 CorrectDelayedTyposInExpr(TheCallResult.get());
1370 return Res;
1371 }
1372 case Builtin::BI__builtin_dump_struct: {
1373 // We first want to ensure we are called with 2 arguments
1374 if (checkArgCount(*this, TheCall, 2))
1375 return ExprError();
1376 // Ensure that the first argument is of type 'struct XX *'
1377 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1378 const QualType PtrArgType = PtrArg->getType();
1379 if (!PtrArgType->isPointerType() ||
1380 !PtrArgType->getPointeeType()->isRecordType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001381 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman68d50642018-06-19 14:53:20 +00001382 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1383 << "structure pointer";
1384 return ExprError();
Aaron Ballman06525342018-04-10 21:58:13 +00001385 }
1386
1387 // Ensure that the second argument is of type 'FunctionType'
1388 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1389 const QualType FnPtrArgType = FnPtrArg->getType();
1390 if (!FnPtrArgType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001391 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1392 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1393 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001394 return ExprError();
1395 }
1396
1397 const auto *FuncType =
1398 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1399
1400 if (!FuncType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001401 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1402 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1403 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001404 return ExprError();
1405 }
1406
1407 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1408 if (!FT->getNumParams()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001409 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001410 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1411 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1412 return ExprError();
1413 }
1414 QualType PT = FT->getParamType(0);
1415 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1416 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1417 !PT->getPointeeType().isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001418 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001419 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1420 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1421 return ExprError();
1422 }
1423 }
1424
1425 TheCall->setType(Context.IntTy);
1426 break;
1427 }
Yonghong Song048493f2019-07-09 04:21:50 +00001428 case Builtin::BI__builtin_preserve_access_index:
1429 if (SemaBuiltinPreserveAI(*this, TheCall))
1430 return ExprError();
1431 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001432 case Builtin::BI__builtin_call_with_static_chain:
1433 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1434 return ExprError();
1435 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001436 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001437 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001438 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1439 diag::err_seh___except_block))
1440 return ExprError();
1441 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001442 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001443 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001444 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1445 diag::err_seh___except_filter))
1446 return ExprError();
1447 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001448 case Builtin::BI__GetExceptionInfo:
1449 if (checkArgCount(*this, TheCall, 1))
1450 return ExprError();
1451
1452 if (CheckCXXThrowOperand(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001453 TheCall->getBeginLoc(),
David Majnemerba3e5ec2015-03-13 18:26:17 +00001454 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1455 TheCall))
1456 return ExprError();
1457
1458 TheCall->setType(Context.VoidPtrTy);
1459 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001460 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001461 case Builtin::BIread_pipe:
1462 case Builtin::BIwrite_pipe:
1463 // Since those two functions are declared with var args, we need a semantic
1464 // check for the argument.
1465 if (SemaBuiltinRWPipe(*this, TheCall))
1466 return ExprError();
1467 break;
1468 case Builtin::BIreserve_read_pipe:
1469 case Builtin::BIreserve_write_pipe:
1470 case Builtin::BIwork_group_reserve_read_pipe:
1471 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001472 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1473 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001474 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001475 case Builtin::BIsub_group_reserve_read_pipe:
1476 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001477 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1478 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001479 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001480 break;
1481 case Builtin::BIcommit_read_pipe:
1482 case Builtin::BIcommit_write_pipe:
1483 case Builtin::BIwork_group_commit_read_pipe:
1484 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001485 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1486 return ExprError();
1487 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001488 case Builtin::BIsub_group_commit_read_pipe:
1489 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001490 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1491 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001492 return ExprError();
1493 break;
1494 case Builtin::BIget_pipe_num_packets:
1495 case Builtin::BIget_pipe_max_packets:
1496 if (SemaBuiltinPipePackets(*this, TheCall))
1497 return ExprError();
1498 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001499 case Builtin::BIto_global:
1500 case Builtin::BIto_local:
1501 case Builtin::BIto_private:
1502 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1503 return ExprError();
1504 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001505 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1506 case Builtin::BIenqueue_kernel:
1507 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1508 return ExprError();
1509 break;
1510 case Builtin::BIget_kernel_work_group_size:
1511 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1512 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1513 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001514 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001515 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1516 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1517 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1518 return ExprError();
1519 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001520 case Builtin::BI__builtin_os_log_format:
1521 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001522 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001523 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001524 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001525 }
Richard Smith760520b2014-06-03 23:27:44 +00001526
Nate Begeman4904e322010-06-08 02:47:44 +00001527 // Since the target specific builtins for each arch overlap, only check those
1528 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001529 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001530 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001531 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001532 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001533 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001534 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001535 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1536 return ExprError();
1537 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001538 case llvm::Triple::aarch64:
1539 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001540 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001541 return ExprError();
1542 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001543 case llvm::Triple::hexagon:
1544 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1545 return ExprError();
1546 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001547 case llvm::Triple::mips:
1548 case llvm::Triple::mipsel:
1549 case llvm::Triple::mips64:
1550 case llvm::Triple::mips64el:
1551 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1552 return ExprError();
1553 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001554 case llvm::Triple::systemz:
1555 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1556 return ExprError();
1557 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001558 case llvm::Triple::x86:
1559 case llvm::Triple::x86_64:
1560 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1561 return ExprError();
1562 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001563 case llvm::Triple::ppc:
1564 case llvm::Triple::ppc64:
1565 case llvm::Triple::ppc64le:
1566 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1567 return ExprError();
1568 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001569 default:
1570 break;
1571 }
1572 }
1573
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001574 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001575}
1576
Nate Begeman91e1fea2010-06-14 05:21:25 +00001577// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001578static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001579 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001580 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001581 switch (Type.getEltType()) {
1582 case NeonTypeFlags::Int8:
1583 case NeonTypeFlags::Poly8:
1584 return shift ? 7 : (8 << IsQuad) - 1;
1585 case NeonTypeFlags::Int16:
1586 case NeonTypeFlags::Poly16:
1587 return shift ? 15 : (4 << IsQuad) - 1;
1588 case NeonTypeFlags::Int32:
1589 return shift ? 31 : (2 << IsQuad) - 1;
1590 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001591 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001592 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001593 case NeonTypeFlags::Poly128:
1594 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001595 case NeonTypeFlags::Float16:
1596 assert(!shift && "cannot shift float types!");
1597 return (4 << IsQuad) - 1;
1598 case NeonTypeFlags::Float32:
1599 assert(!shift && "cannot shift float types!");
1600 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001601 case NeonTypeFlags::Float64:
1602 assert(!shift && "cannot shift float types!");
1603 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001604 }
David Blaikie8a40f702012-01-17 06:56:22 +00001605 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001606}
1607
Bob Wilsone4d77232011-11-08 05:04:11 +00001608/// getNeonEltType - Return the QualType corresponding to the elements of
1609/// the vector type specified by the NeonTypeFlags. This is used to check
1610/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001611static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001612 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001613 switch (Flags.getEltType()) {
1614 case NeonTypeFlags::Int8:
1615 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1616 case NeonTypeFlags::Int16:
1617 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1618 case NeonTypeFlags::Int32:
1619 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1620 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001621 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001622 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1623 else
1624 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1625 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001626 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001627 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001628 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001629 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001630 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001631 if (IsInt64Long)
1632 return Context.UnsignedLongTy;
1633 else
1634 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001635 case NeonTypeFlags::Poly128:
1636 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001637 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001638 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001639 case NeonTypeFlags::Float32:
1640 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001641 case NeonTypeFlags::Float64:
1642 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001643 }
David Blaikie8a40f702012-01-17 06:56:22 +00001644 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001645}
1646
Tim Northover12670412014-02-19 10:37:05 +00001647bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001648 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001649 uint64_t mask = 0;
1650 unsigned TV = 0;
1651 int PtrArgNum = -1;
1652 bool HasConstPtr = false;
1653 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001654#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001655#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001656#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001657#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001658 }
1659
1660 // For NEON intrinsics which are overloaded on vector element type, validate
1661 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001662 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001663 if (mask) {
1664 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1665 return true;
1666
1667 TV = Result.getLimitedValue(64);
1668 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001669 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1670 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001671 }
1672
1673 if (PtrArgNum >= 0) {
1674 // Check that pointer arguments have the specified type.
1675 Expr *Arg = TheCall->getArg(PtrArgNum);
1676 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1677 Arg = ICE->getSubExpr();
1678 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1679 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001680
Tim Northovera2ee4332014-03-29 15:09:45 +00001681 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001682 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1683 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001684 bool IsInt64Long =
1685 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1686 QualType EltTy =
1687 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001688 if (HasConstPtr)
1689 EltTy = EltTy.withConst();
1690 QualType LHSTy = Context.getPointerType(EltTy);
1691 AssignConvertType ConvTy;
1692 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1693 if (RHS.isInvalid())
1694 return true;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001695 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
Tim Northover2fe823a2013-08-01 09:23:19 +00001696 RHS.get(), AA_Assigning))
1697 return true;
1698 }
1699
1700 // For NEON intrinsics which take an immediate value as part of the
1701 // instruction, range check them here.
1702 unsigned i = 0, l = 0, u = 0;
1703 switch (BuiltinID) {
1704 default:
1705 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001706 #define GET_NEON_IMMEDIATE_CHECK
1707 #include "clang/Basic/arm_neon.inc"
1708 #include "clang/Basic/arm_fp16.inc"
1709 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001710 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001711
Richard Sandiford28940af2014-04-16 08:47:51 +00001712 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001713}
1714
Tim Northovera2ee4332014-03-29 15:09:45 +00001715bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1716 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001717 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001718 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001719 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001720 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001721 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001722 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1723 BuiltinID == AArch64::BI__builtin_arm_strex ||
1724 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001725 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001726 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001727 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1728 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1729 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001730
1731 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1732
1733 // Ensure that we have the proper number of arguments.
1734 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1735 return true;
1736
1737 // Inspect the pointer argument of the atomic builtin. This should always be
1738 // a pointer type, whose element is an integral scalar or pointer type.
1739 // Because it is a pointer type, we don't have to worry about any implicit
1740 // casts here.
1741 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1742 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1743 if (PointerArgRes.isInvalid())
1744 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001745 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001746
1747 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1748 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001749 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1750 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001751 return true;
1752 }
1753
1754 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1755 // task is to insert the appropriate casts into the AST. First work out just
1756 // what the appropriate type is.
1757 QualType ValType = pointerType->getPointeeType();
1758 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1759 if (IsLdrex)
1760 AddrType.addConst();
1761
1762 // Issue a warning if the cast is dodgy.
1763 CastKind CastNeeded = CK_NoOp;
1764 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1765 CastNeeded = CK_BitCast;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001766 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1767 << PointerArg->getType() << Context.getPointerType(AddrType)
1768 << AA_Passing << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001769 }
1770
1771 // Finally, do the cast and replace the argument with the corrected version.
1772 AddrType = Context.getPointerType(AddrType);
1773 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1774 if (PointerArgRes.isInvalid())
1775 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001776 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001777
1778 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1779
1780 // In general, we allow ints, floats and pointers to be loaded and stored.
1781 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1782 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001783 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1784 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001785 return true;
1786 }
1787
1788 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001789 if (Context.getTypeSize(ValType) > MaxWidth) {
1790 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001791 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1792 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001793 return true;
1794 }
1795
1796 switch (ValType.getObjCLifetime()) {
1797 case Qualifiers::OCL_None:
1798 case Qualifiers::OCL_ExplicitNone:
1799 // okay
1800 break;
1801
1802 case Qualifiers::OCL_Weak:
1803 case Qualifiers::OCL_Strong:
1804 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001805 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1806 << ValType << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001807 return true;
1808 }
1809
Tim Northover6aacd492013-07-16 09:47:53 +00001810 if (IsLdrex) {
1811 TheCall->setType(ValType);
1812 return false;
1813 }
1814
1815 // Initialize the argument to be stored.
1816 ExprResult ValArg = TheCall->getArg(0);
1817 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1818 Context, ValType, /*consume*/ false);
1819 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1820 if (ValArg.isInvalid())
1821 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001822 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001823
1824 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1825 // but the custom checker bypasses all default analysis.
1826 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001827 return false;
1828}
1829
Nate Begeman4904e322010-06-08 02:47:44 +00001830bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001831 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001832 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1833 BuiltinID == ARM::BI__builtin_arm_strex ||
1834 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001835 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001836 }
1837
Yi Kong26d104a2014-08-13 19:18:14 +00001838 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1839 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1840 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1841 }
1842
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001843 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1844 BuiltinID == ARM::BI__builtin_arm_wsr64)
1845 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1846
1847 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1848 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1849 BuiltinID == ARM::BI__builtin_arm_wsr ||
1850 BuiltinID == ARM::BI__builtin_arm_wsrp)
1851 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1852
Tim Northover12670412014-02-19 10:37:05 +00001853 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1854 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001855
Yi Kong4efadfb2014-07-03 16:01:25 +00001856 // For intrinsics which take an immediate value as part of the instruction,
1857 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001858 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001859 switch (BuiltinID) {
1860 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001861 case ARM::BI__builtin_arm_ssat:
1862 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1863 case ARM::BI__builtin_arm_usat:
1864 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1865 case ARM::BI__builtin_arm_ssat16:
1866 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1867 case ARM::BI__builtin_arm_usat16:
1868 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001869 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001870 case ARM::BI__builtin_arm_vcvtr_d:
1871 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001872 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001873 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001874 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001875 case ARM::BI__builtin_arm_dbg:
1876 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001877 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001878}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001879
Tim Northover573cbee2014-05-24 12:52:07 +00001880bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001881 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001882 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001883 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1884 BuiltinID == AArch64::BI__builtin_arm_strex ||
1885 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001886 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1887 }
1888
Yi Konga5548432014-08-13 19:18:20 +00001889 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1890 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1891 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1892 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1893 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1894 }
1895
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001896 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1897 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001898 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001899
Javed Absar18b0c402019-04-26 21:08:11 +00001900 // Memory Tagging Extensions (MTE) Intrinsics
1901 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1902 BuiltinID == AArch64::BI__builtin_arm_addg ||
1903 BuiltinID == AArch64::BI__builtin_arm_gmi ||
1904 BuiltinID == AArch64::BI__builtin_arm_ldg ||
1905 BuiltinID == AArch64::BI__builtin_arm_stg ||
1906 BuiltinID == AArch64::BI__builtin_arm_subp) {
1907 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1908 }
1909
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001910 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1911 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1912 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1913 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1914 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1915
Mandeep Singh Grang2147b1a2018-10-18 23:35:35 +00001916 // Only check the valid encoding range. Any constant in this range would be
1917 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1918 // an exception for incorrect registers. This matches MSVC behavior.
1919 if (BuiltinID == AArch64::BI_ReadStatusReg ||
1920 BuiltinID == AArch64::BI_WriteStatusReg)
1921 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1922
Mandeep Singh Grangecc82ef2018-10-04 22:32:42 +00001923 if (BuiltinID == AArch64::BI__getReg)
1924 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1925
Tim Northovera2ee4332014-03-29 15:09:45 +00001926 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1927 return true;
1928
Yi Kong19a29ac2014-07-17 10:52:06 +00001929 // For intrinsics which take an immediate value as part of the instruction,
1930 // range check them here.
1931 unsigned i = 0, l = 0, u = 0;
1932 switch (BuiltinID) {
1933 default: return false;
1934 case AArch64::BI__builtin_arm_dmb:
1935 case AArch64::BI__builtin_arm_dsb:
1936 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
Momchil Velikova36d3142019-07-31 12:52:17 +00001937 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
Yi Kong19a29ac2014-07-17 10:52:06 +00001938 }
1939
Yi Kong19a29ac2014-07-17 10:52:06 +00001940 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001941}
1942
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001943bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001944 struct BuiltinAndString {
1945 unsigned BuiltinID;
1946 const char *Str;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001947 };
1948
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001949 static BuiltinAndString ValidCPU[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00001950 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1951 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1952 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1953 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1954 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1955 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1956 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1957 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1958 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1959 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1960 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1961 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1962 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1963 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1964 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1965 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1966 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1967 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1968 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1969 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1970 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1971 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1972 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001973 };
1974
1975 static BuiltinAndString ValidHVX[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00001976 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1977 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1978 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1979 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1980 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1981 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1982 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1983 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1984 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1985 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1986 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1987 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1988 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1989 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1990 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1991 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1992 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1993 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1994 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1995 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1996 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1997 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1998 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1999 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
2000 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
2001 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
2002 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2003 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2004 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2005 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2006 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2007 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2008 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2009 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2010 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2011 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2012 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2013 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2014 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2015 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2016 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2017 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2018 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2019 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2020 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2021 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2022 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2023 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2024 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2025 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2026 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2027 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2028 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2029 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2030 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2031 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2032 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2033 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2034 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2035 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2036 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2037 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2038 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2039 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2040 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2041 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2042 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2043 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2044 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2045 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2046 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2047 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2048 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2049 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2050 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2051 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2052 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2053 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2054 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2055 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2056 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2057 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2058 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2059 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2060 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2061 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2062 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2063 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2064 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2065 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2066 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2067 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2068 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2069 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2070 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2071 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2072 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2073 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2074 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2075 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2076 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2077 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2078 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2079 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2080 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2081 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2082 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2083 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2084 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2085 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2086 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2087 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2088 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2089 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2090 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2091 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2092 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2093 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2094 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2095 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2096 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2097 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2098 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2099 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2100 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2101 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2102 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2103 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2104 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2105 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2106 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2107 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2108 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2109 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2110 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2111 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2112 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2113 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2114 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2115 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2116 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2117 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2118 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2119 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2120 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2121 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2122 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2123 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2124 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2125 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2126 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2127 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2128 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2129 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2130 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2131 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2132 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2133 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2134 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2135 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2136 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2137 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2138 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2139 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2140 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2141 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2142 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2143 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2144 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2145 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2146 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2147 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2148 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2149 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2150 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2151 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2152 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2153 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2154 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2155 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2156 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2157 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2158 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2159 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2160 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2161 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2162 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2163 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2164 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2165 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2166 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2167 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2168 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2169 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2170 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2171 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2172 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2173 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2174 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2175 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2176 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2177 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2178 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2179 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2180 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2181 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2182 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2183 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2184 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2185 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2186 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2187 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2188 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2189 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2190 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2191 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2192 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2193 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2194 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2195 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2196 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2197 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2198 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2199 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2200 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2201 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2202 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2203 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2204 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2205 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2206 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2207 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2208 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2209 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2210 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2211 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2212 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2213 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2214 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2215 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2216 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2217 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2218 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2219 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2220 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2221 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2222 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2223 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2224 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2225 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2226 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2227 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2228 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2229 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2230 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2231 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2232 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2233 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2234 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2235 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2236 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2237 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2238 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2239 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2240 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2241 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2242 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2243 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2244 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2245 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2246 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2247 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2248 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2249 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2250 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2251 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2252 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2253 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2254 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2255 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2256 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2257 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2258 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2259 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2260 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2261 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2262 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2263 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2264 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2265 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2266 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2267 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2268 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2269 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2270 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2271 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2272 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2273 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2274 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2275 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2276 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2277 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2278 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2279 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2280 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2281 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2282 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2283 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2284 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2285 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2286 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2287 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2288 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2289 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2290 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2291 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2292 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2293 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2294 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2295 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2296 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2297 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2298 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2299 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2300 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2301 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2302 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2303 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2304 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2305 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2306 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2307 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2308 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2309 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2310 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2311 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2312 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2313 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2314 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2315 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2316 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2317 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2318 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2319 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2320 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2321 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2322 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2323 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2324 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2325 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2326 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2327 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2328 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2329 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2330 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2331 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2332 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2333 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2334 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2335 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2336 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2337 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2338 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2339 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2340 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2341 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2342 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2343 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2344 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2345 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2346 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2347 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2348 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2349 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2350 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2351 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2352 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2353 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2354 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2355 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2356 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2357 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2358 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2359 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2360 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2361 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2362 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2363 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2364 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2365 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2366 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2367 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2368 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2369 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2370 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2371 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2372 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2373 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2374 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2375 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2376 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2377 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2397 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2398 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2399 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2400 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2401 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2402 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2403 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2404 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2405 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2406 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2407 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2408 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2409 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2410 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2411 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2412 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2413 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2414 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2415 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2416 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2417 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2418 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2419 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2420 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2421 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2422 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2423 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2424 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2425 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2426 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2427 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2428 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2467 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2468 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2469 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2470 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2471 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2472 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2473 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2474 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2475 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2476 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2477 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2478 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2479 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2480 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2481 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2482 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2483 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2484 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2485 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2486 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2487 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2488 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2489 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2490 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2491 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2492 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2493 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2494 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2495 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2496 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2497 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2498 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2499 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2500 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2501 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2502 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2503 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2504 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2505 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2506 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2507 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2508 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2509 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2510 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2511 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2512 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2513 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2514 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2515 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2516 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2517 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2518 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2519 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2520 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2521 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2522 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2523 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2524 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2525 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2526 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2527 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2528 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2529 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2530 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2531 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2532 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2533 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2534 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2535 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2536 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2537 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2538 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2539 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2540 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2541 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2542 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2543 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002544 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2545 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2546 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2547 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002548 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2549 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2550 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2551 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2552 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2553 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2554 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2555 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2556 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2557 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2558 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2559 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2560 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2561 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2562 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2563 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2564 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2565 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2566 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2567 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2568 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2569 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2570 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2571 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002572 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2573 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2574 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2575 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002576 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2577 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2578 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2579 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2580 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2581 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2582 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2583 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2584 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2585 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2586 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2587 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2588 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2589 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2590 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2591 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2592 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2593 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2594 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2595 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2596 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2597 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2598 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2599 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2600 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2601 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2602 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2603 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2604 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2605 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2606 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2607 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2608 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2609 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2610 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2611 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2612 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2613 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2614 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2615 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2616 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2617 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2618 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2619 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2620 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2621 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2622 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2623 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2624 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2625 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2626 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2627 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2628 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2629 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2630 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2631 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2632 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2633 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2634 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2635 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2636 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2637 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2638 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2639 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2640 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2641 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2642 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2643 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2644 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2645 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2646 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2647 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2648 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2649 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2650 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2651 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2652 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2653 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2654 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2655 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2656 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2657 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2658 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2659 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2660 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2661 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2662 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2663 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2664 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2665 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2666 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2667 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2668 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2669 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2670 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2671 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2672 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2673 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2674 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2675 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2676 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2677 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2678 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2679 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2680 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2681 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2682 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2683 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2684 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2685 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2686 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2687 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2688 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2689 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2690 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2691 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2692 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2693 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2694 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2695 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2696 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2697 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2698 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2699 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2700 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2701 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2702 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2703 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2704 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2705 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2706 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2707 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002708 };
2709
2710 // Sort the tables on first execution so we can binary search them.
2711 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2712 return LHS.BuiltinID < RHS.BuiltinID;
2713 };
2714 static const bool SortOnce =
Mandeep Singh Grang50dadaa42019-01-14 23:45:58 +00002715 (llvm::sort(ValidCPU, SortCmp),
2716 llvm::sort(ValidHVX, SortCmp), true);
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002717 (void)SortOnce;
2718 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2719 return BI.BuiltinID < BuiltinID;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002720 };
2721
2722 const TargetInfo &TI = Context.getTargetInfo();
2723
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002724 const BuiltinAndString *FC =
Fangrui Song7264a472019-07-03 08:13:17 +00002725 llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002726 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002727 const TargetOptions &Opts = TI.getTargetOpts();
2728 StringRef CPU = Opts.CPU;
2729 if (!CPU.empty()) {
2730 assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2731 CPU.consume_front("hexagon");
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002732 SmallVector<StringRef, 3> CPUs;
2733 StringRef(FC->Str).split(CPUs, ',');
2734 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002735 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002736 diag::err_hexagon_builtin_unsupported_cpu);
2737 }
2738 }
2739
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002740 const BuiltinAndString *FH =
Fangrui Song7264a472019-07-03 08:13:17 +00002741 llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002742 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002743 if (!TI.hasFeature("hvx"))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002744 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002745 diag::err_hexagon_builtin_requires_hvx);
2746
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002747 SmallVector<StringRef, 3> HVXs;
2748 StringRef(FH->Str).split(HVXs, ',');
2749 bool IsValid = llvm::any_of(HVXs,
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002750 [&TI] (StringRef V) {
2751 std::string F = "hvx" + V.str();
2752 return TI.hasFeature(F);
2753 });
2754 if (!IsValid)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002755 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002756 diag::err_hexagon_builtin_unsupported_hvx);
2757 }
2758
2759 return false;
2760}
2761
2762bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002763 struct ArgInfo {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002764 uint8_t OpNum;
2765 bool IsSigned;
2766 uint8_t BitWidth;
2767 uint8_t Align;
2768 };
2769 struct BuiltinInfo {
2770 unsigned BuiltinID;
2771 ArgInfo Infos[2];
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002772 };
2773
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002774 static BuiltinInfo Infos[] = {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002775 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2776 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2777 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2778 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
2779 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2780 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2781 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2782 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2783 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2784 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2785 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2786
2787 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2788 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2789 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2790 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2791 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2792 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2793 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2794 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2795 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2796 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2797 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2798
2799 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2800 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2801 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2802 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2803 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2804 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2805 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2806 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2807 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2808 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2809 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2811 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2812 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2813 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2814 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2815 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2816 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2817 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2818 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2819 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2820 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2821 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2822 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2823 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2824 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2825 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2826 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2827 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2828 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2829 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2830 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2841 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2842 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2843 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2844 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2851 {{ 1, false, 6, 0 }} },
2852 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2857 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2859 {{ 1, false, 5, 0 }} },
2860 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
2861 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
2862 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
2863 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
2864 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
2865 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
2866 { 2, false, 5, 0 }} },
2867 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
2868 { 2, false, 6, 0 }} },
2869 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
2870 { 3, false, 5, 0 }} },
2871 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
2872 { 3, false, 6, 0 }} },
2873 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
2883 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
2884 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
2885 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
2886 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
2887 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
2888 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2889 {{ 2, false, 4, 0 },
2890 { 3, false, 5, 0 }} },
2891 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2892 {{ 2, false, 4, 0 },
2893 { 3, false, 5, 0 }} },
2894 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2895 {{ 2, false, 4, 0 },
2896 { 3, false, 5, 0 }} },
2897 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2898 {{ 2, false, 4, 0 },
2899 { 3, false, 5, 0 }} },
2900 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
2901 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
2902 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
2903 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
2904 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
2905 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
2906 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
2907 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
2908 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
2909 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
2910 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
2911 { 2, false, 5, 0 }} },
2912 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
2913 { 2, false, 6, 0 }} },
2914 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
2915 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
2916 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
2917 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
2918 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
2919 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
2920 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
2921 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
2922 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2923 {{ 1, false, 4, 0 }} },
2924 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
2925 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2926 {{ 1, false, 4, 0 }} },
2927 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
2935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
2936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
2937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
2938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
2939 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
2940 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
2941 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
2942 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
2943 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
2945 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
2946 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2947 {{ 3, false, 1, 0 }} },
2948 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
2949 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
2950 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
2951 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2952 {{ 3, false, 1, 0 }} },
2953 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
2954 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
2955 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
2956 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2957 {{ 3, false, 1, 0 }} },
2958 };
2959
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002960 // Use a dynamically initialized static to sort the table exactly once on
2961 // first run.
2962 static const bool SortOnce =
Mandeep Singh Grang50dadaa42019-01-14 23:45:58 +00002963 (llvm::sort(Infos,
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002964 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2965 return LHS.BuiltinID < RHS.BuiltinID;
2966 }),
2967 true);
2968 (void)SortOnce;
2969
Fangrui Song7264a472019-07-03 08:13:17 +00002970 const BuiltinInfo *F = llvm::partition_point(
2971 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002972 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002973 return false;
2974
2975 bool Error = false;
2976
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002977 for (const ArgInfo &A : F->Infos) {
2978 // Ignore empty ArgInfo elements.
2979 if (A.BitWidth == 0)
2980 continue;
2981
2982 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2983 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002984 if (!A.Align) {
2985 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2986 } else {
2987 unsigned M = 1 << A.Align;
2988 Min *= M;
2989 Max *= M;
2990 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2991 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2992 }
2993 }
2994 return Error;
2995}
2996
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002997bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2998 CallExpr *TheCall) {
2999 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
3000 CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3001}
3002
3003
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003004// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
3005// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3006// ordering for DSP is unspecified. MSA is ordered by the data format used
3007// by the underlying instruction i.e., df/m, df/n and then by size.
3008//
3009// FIXME: The size tests here should instead be tablegen'd along with the
3010// definitions from include/clang/Basic/BuiltinsMips.def.
3011// FIXME: GCC is strict on signedness for some of these intrinsics, we should
3012// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003013bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003014 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003015 switch (BuiltinID) {
3016 default: return false;
3017 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3018 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00003019 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3020 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3021 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3022 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3023 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003024 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003025 // df/m field.
3026 // These intrinsics take an unsigned 3 bit immediate.
3027 case Mips::BI__builtin_msa_bclri_b:
3028 case Mips::BI__builtin_msa_bnegi_b:
3029 case Mips::BI__builtin_msa_bseti_b:
3030 case Mips::BI__builtin_msa_sat_s_b:
3031 case Mips::BI__builtin_msa_sat_u_b:
3032 case Mips::BI__builtin_msa_slli_b:
3033 case Mips::BI__builtin_msa_srai_b:
3034 case Mips::BI__builtin_msa_srari_b:
3035 case Mips::BI__builtin_msa_srli_b:
3036 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3037 case Mips::BI__builtin_msa_binsli_b:
3038 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3039 // These intrinsics take an unsigned 4 bit immediate.
3040 case Mips::BI__builtin_msa_bclri_h:
3041 case Mips::BI__builtin_msa_bnegi_h:
3042 case Mips::BI__builtin_msa_bseti_h:
3043 case Mips::BI__builtin_msa_sat_s_h:
3044 case Mips::BI__builtin_msa_sat_u_h:
3045 case Mips::BI__builtin_msa_slli_h:
3046 case Mips::BI__builtin_msa_srai_h:
3047 case Mips::BI__builtin_msa_srari_h:
3048 case Mips::BI__builtin_msa_srli_h:
3049 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3050 case Mips::BI__builtin_msa_binsli_h:
3051 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003052 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003053 // The first block of intrinsics actually have an unsigned 5 bit field,
3054 // not a df/n field.
Simon Atanasyanc7f0b332019-05-29 14:59:32 +00003055 case Mips::BI__builtin_msa_cfcmsa:
3056 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003057 case Mips::BI__builtin_msa_clei_u_b:
3058 case Mips::BI__builtin_msa_clei_u_h:
3059 case Mips::BI__builtin_msa_clei_u_w:
3060 case Mips::BI__builtin_msa_clei_u_d:
3061 case Mips::BI__builtin_msa_clti_u_b:
3062 case Mips::BI__builtin_msa_clti_u_h:
3063 case Mips::BI__builtin_msa_clti_u_w:
3064 case Mips::BI__builtin_msa_clti_u_d:
3065 case Mips::BI__builtin_msa_maxi_u_b:
3066 case Mips::BI__builtin_msa_maxi_u_h:
3067 case Mips::BI__builtin_msa_maxi_u_w:
3068 case Mips::BI__builtin_msa_maxi_u_d:
3069 case Mips::BI__builtin_msa_mini_u_b:
3070 case Mips::BI__builtin_msa_mini_u_h:
3071 case Mips::BI__builtin_msa_mini_u_w:
3072 case Mips::BI__builtin_msa_mini_u_d:
3073 case Mips::BI__builtin_msa_addvi_b:
3074 case Mips::BI__builtin_msa_addvi_h:
3075 case Mips::BI__builtin_msa_addvi_w:
3076 case Mips::BI__builtin_msa_addvi_d:
3077 case Mips::BI__builtin_msa_bclri_w:
3078 case Mips::BI__builtin_msa_bnegi_w:
3079 case Mips::BI__builtin_msa_bseti_w:
3080 case Mips::BI__builtin_msa_sat_s_w:
3081 case Mips::BI__builtin_msa_sat_u_w:
3082 case Mips::BI__builtin_msa_slli_w:
3083 case Mips::BI__builtin_msa_srai_w:
3084 case Mips::BI__builtin_msa_srari_w:
3085 case Mips::BI__builtin_msa_srli_w:
3086 case Mips::BI__builtin_msa_srlri_w:
3087 case Mips::BI__builtin_msa_subvi_b:
3088 case Mips::BI__builtin_msa_subvi_h:
3089 case Mips::BI__builtin_msa_subvi_w:
3090 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3091 case Mips::BI__builtin_msa_binsli_w:
3092 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3093 // These intrinsics take an unsigned 6 bit immediate.
3094 case Mips::BI__builtin_msa_bclri_d:
3095 case Mips::BI__builtin_msa_bnegi_d:
3096 case Mips::BI__builtin_msa_bseti_d:
3097 case Mips::BI__builtin_msa_sat_s_d:
3098 case Mips::BI__builtin_msa_sat_u_d:
3099 case Mips::BI__builtin_msa_slli_d:
3100 case Mips::BI__builtin_msa_srai_d:
3101 case Mips::BI__builtin_msa_srari_d:
3102 case Mips::BI__builtin_msa_srli_d:
3103 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3104 case Mips::BI__builtin_msa_binsli_d:
3105 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3106 // These intrinsics take a signed 5 bit immediate.
3107 case Mips::BI__builtin_msa_ceqi_b:
3108 case Mips::BI__builtin_msa_ceqi_h:
3109 case Mips::BI__builtin_msa_ceqi_w:
3110 case Mips::BI__builtin_msa_ceqi_d:
3111 case Mips::BI__builtin_msa_clti_s_b:
3112 case Mips::BI__builtin_msa_clti_s_h:
3113 case Mips::BI__builtin_msa_clti_s_w:
3114 case Mips::BI__builtin_msa_clti_s_d:
3115 case Mips::BI__builtin_msa_clei_s_b:
3116 case Mips::BI__builtin_msa_clei_s_h:
3117 case Mips::BI__builtin_msa_clei_s_w:
3118 case Mips::BI__builtin_msa_clei_s_d:
3119 case Mips::BI__builtin_msa_maxi_s_b:
3120 case Mips::BI__builtin_msa_maxi_s_h:
3121 case Mips::BI__builtin_msa_maxi_s_w:
3122 case Mips::BI__builtin_msa_maxi_s_d:
3123 case Mips::BI__builtin_msa_mini_s_b:
3124 case Mips::BI__builtin_msa_mini_s_h:
3125 case Mips::BI__builtin_msa_mini_s_w:
3126 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3127 // These intrinsics take an unsigned 8 bit immediate.
3128 case Mips::BI__builtin_msa_andi_b:
3129 case Mips::BI__builtin_msa_nori_b:
3130 case Mips::BI__builtin_msa_ori_b:
3131 case Mips::BI__builtin_msa_shf_b:
3132 case Mips::BI__builtin_msa_shf_h:
3133 case Mips::BI__builtin_msa_shf_w:
3134 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3135 case Mips::BI__builtin_msa_bseli_b:
3136 case Mips::BI__builtin_msa_bmnzi_b:
3137 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3138 // df/n format
3139 // These intrinsics take an unsigned 4 bit immediate.
3140 case Mips::BI__builtin_msa_copy_s_b:
3141 case Mips::BI__builtin_msa_copy_u_b:
3142 case Mips::BI__builtin_msa_insve_b:
3143 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003144 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3145 // These intrinsics take an unsigned 3 bit immediate.
3146 case Mips::BI__builtin_msa_copy_s_h:
3147 case Mips::BI__builtin_msa_copy_u_h:
3148 case Mips::BI__builtin_msa_insve_h:
3149 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003150 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3151 // These intrinsics take an unsigned 2 bit immediate.
3152 case Mips::BI__builtin_msa_copy_s_w:
3153 case Mips::BI__builtin_msa_copy_u_w:
3154 case Mips::BI__builtin_msa_insve_w:
3155 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003156 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3157 // These intrinsics take an unsigned 1 bit immediate.
3158 case Mips::BI__builtin_msa_copy_s_d:
3159 case Mips::BI__builtin_msa_copy_u_d:
3160 case Mips::BI__builtin_msa_insve_d:
3161 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003162 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3163 // Memory offsets and immediate loads.
3164 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00003165 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003166 case Mips::BI__builtin_msa_ldi_h:
3167 case Mips::BI__builtin_msa_ldi_w:
3168 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
Aleksandar Beserminjie5921162018-11-07 11:37:05 +00003169 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3170 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3171 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3172 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3173 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3174 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3175 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3176 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00003177 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003178
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003179 if (!m)
3180 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3181
3182 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3183 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003184}
3185
Kit Bartone50adcb2015-03-30 19:40:59 +00003186bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3187 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003188 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3189 BuiltinID == PPC::BI__builtin_divdeu ||
3190 BuiltinID == PPC::BI__builtin_bpermd;
3191 bool IsTarget64Bit = Context.getTargetInfo()
3192 .getTypeWidth(Context
3193 .getTargetInfo()
3194 .getIntPtrType()) == 64;
3195 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3196 BuiltinID == PPC::BI__builtin_divweu ||
3197 BuiltinID == PPC::BI__builtin_divde ||
3198 BuiltinID == PPC::BI__builtin_divdeu;
3199
3200 if (Is64BitBltin && !IsTarget64Bit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003201 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3202 << TheCall->getSourceRange();
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003203
3204 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3205 (BuiltinID == PPC::BI__builtin_bpermd &&
3206 !Context.getTargetInfo().hasFeature("bpermd")))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003207 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003208 << TheCall->getSourceRange();
3209
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003210 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3211 if (!Context.getTargetInfo().hasFeature("vsx"))
3212 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3213 << TheCall->getSourceRange();
3214 return false;
3215 };
3216
Kit Bartone50adcb2015-03-30 19:40:59 +00003217 switch (BuiltinID) {
3218 default: return false;
3219 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3220 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3221 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3222 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Jinsong Ji53091892019-09-04 14:01:47 +00003223 case PPC::BI__builtin_altivec_dss:
3224 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
Kit Bartone50adcb2015-03-30 19:40:59 +00003225 case PPC::BI__builtin_tbegin:
3226 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3227 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3228 case PPC::BI__builtin_tabortwc:
3229 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3230 case PPC::BI__builtin_tabortwci:
3231 case PPC::BI__builtin_tabortdci:
3232 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3233 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Jinsong Jia71c1992019-09-04 15:22:26 +00003234 case PPC::BI__builtin_altivec_dst:
3235 case PPC::BI__builtin_altivec_dstt:
3236 case PPC::BI__builtin_altivec_dstst:
3237 case PPC::BI__builtin_altivec_dststt:
3238 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
Tony Jiangbbc48e92017-05-24 15:13:32 +00003239 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00003240 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00003241 return SemaBuiltinVSX(TheCall);
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003242 case PPC::BI__builtin_unpack_vector_int128:
3243 return SemaVSXCheck(TheCall) ||
3244 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3245 case PPC::BI__builtin_pack_vector_int128:
3246 return SemaVSXCheck(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00003247 }
3248 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3249}
3250
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003251bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3252 CallExpr *TheCall) {
3253 if (BuiltinID == SystemZ::BI__builtin_tabort) {
3254 Expr *Arg = TheCall->getArg(0);
3255 llvm::APSInt AbortCode(32);
3256 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3257 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003258 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003259 << Arg->getSourceRange();
3260 }
3261
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003262 // For intrinsics which take an immediate value as part of the instruction,
3263 // range check them here.
3264 unsigned i = 0, l = 0, u = 0;
3265 switch (BuiltinID) {
3266 default: return false;
3267 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3268 case SystemZ::BI__builtin_s390_verimb:
3269 case SystemZ::BI__builtin_s390_verimh:
3270 case SystemZ::BI__builtin_s390_verimf:
3271 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3272 case SystemZ::BI__builtin_s390_vfaeb:
3273 case SystemZ::BI__builtin_s390_vfaeh:
3274 case SystemZ::BI__builtin_s390_vfaef:
3275 case SystemZ::BI__builtin_s390_vfaebs:
3276 case SystemZ::BI__builtin_s390_vfaehs:
3277 case SystemZ::BI__builtin_s390_vfaefs:
3278 case SystemZ::BI__builtin_s390_vfaezb:
3279 case SystemZ::BI__builtin_s390_vfaezh:
3280 case SystemZ::BI__builtin_s390_vfaezf:
3281 case SystemZ::BI__builtin_s390_vfaezbs:
3282 case SystemZ::BI__builtin_s390_vfaezhs:
3283 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003284 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003285 case SystemZ::BI__builtin_s390_vfidb:
3286 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3287 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003288 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003289 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3290 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3291 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3292 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3293 case SystemZ::BI__builtin_s390_vstrcb:
3294 case SystemZ::BI__builtin_s390_vstrch:
3295 case SystemZ::BI__builtin_s390_vstrcf:
3296 case SystemZ::BI__builtin_s390_vstrczb:
3297 case SystemZ::BI__builtin_s390_vstrczh:
3298 case SystemZ::BI__builtin_s390_vstrczf:
3299 case SystemZ::BI__builtin_s390_vstrcbs:
3300 case SystemZ::BI__builtin_s390_vstrchs:
3301 case SystemZ::BI__builtin_s390_vstrcfs:
3302 case SystemZ::BI__builtin_s390_vstrczbs:
3303 case SystemZ::BI__builtin_s390_vstrczhs:
3304 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003305 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3306 case SystemZ::BI__builtin_s390_vfminsb:
3307 case SystemZ::BI__builtin_s390_vfmaxsb:
3308 case SystemZ::BI__builtin_s390_vfmindb:
3309 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigandb98bf602019-07-12 18:14:51 +00003310 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3311 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003312 }
3313 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003314}
3315
Craig Topper5ba2c502015-11-07 08:08:31 +00003316/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3317/// This checks that the target supports __builtin_cpu_supports and
3318/// that the string argument is constant and valid.
3319static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3320 Expr *Arg = TheCall->getArg(0);
3321
3322 // Check if the argument is a string literal.
3323 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003324 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper5ba2c502015-11-07 08:08:31 +00003325 << Arg->getSourceRange();
3326
3327 // Check the contents of the string.
3328 StringRef Feature =
3329 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3330 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003331 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
Craig Topper5ba2c502015-11-07 08:08:31 +00003332 << Arg->getSourceRange();
3333 return false;
3334}
3335
Craig Topper699ae0c2017-08-10 20:28:30 +00003336/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3337/// This checks that the target supports __builtin_cpu_is and
3338/// that the string argument is constant and valid.
3339static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3340 Expr *Arg = TheCall->getArg(0);
3341
3342 // Check if the argument is a string literal.
3343 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003344 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper699ae0c2017-08-10 20:28:30 +00003345 << Arg->getSourceRange();
3346
3347 // Check the contents of the string.
3348 StringRef Feature =
3349 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3350 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003351 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
Craig Topper699ae0c2017-08-10 20:28:30 +00003352 << Arg->getSourceRange();
3353 return false;
3354}
3355
Craig Toppera7e253e2016-09-23 04:48:31 +00003356// Check if the rounding mode is legal.
3357bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3358 // Indicates if this instruction has rounding control or just SAE.
3359 bool HasRC = false;
3360
3361 unsigned ArgNum = 0;
3362 switch (BuiltinID) {
3363 default:
3364 return false;
3365 case X86::BI__builtin_ia32_vcvttsd2si32:
3366 case X86::BI__builtin_ia32_vcvttsd2si64:
3367 case X86::BI__builtin_ia32_vcvttsd2usi32:
3368 case X86::BI__builtin_ia32_vcvttsd2usi64:
3369 case X86::BI__builtin_ia32_vcvttss2si32:
3370 case X86::BI__builtin_ia32_vcvttss2si64:
3371 case X86::BI__builtin_ia32_vcvttss2usi32:
3372 case X86::BI__builtin_ia32_vcvttss2usi64:
3373 ArgNum = 1;
3374 break;
Craig Topper2da60bc2018-06-21 05:01:01 +00003375 case X86::BI__builtin_ia32_maxpd512:
3376 case X86::BI__builtin_ia32_maxps512:
3377 case X86::BI__builtin_ia32_minpd512:
3378 case X86::BI__builtin_ia32_minps512:
3379 ArgNum = 2;
3380 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003381 case X86::BI__builtin_ia32_cvtps2pd512_mask:
3382 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3383 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3384 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3385 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3386 case X86::BI__builtin_ia32_cvttps2dq512_mask:
3387 case X86::BI__builtin_ia32_cvttps2qq512_mask:
3388 case X86::BI__builtin_ia32_cvttps2udq512_mask:
3389 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3390 case X86::BI__builtin_ia32_exp2pd_mask:
3391 case X86::BI__builtin_ia32_exp2ps_mask:
3392 case X86::BI__builtin_ia32_getexppd512_mask:
3393 case X86::BI__builtin_ia32_getexpps512_mask:
3394 case X86::BI__builtin_ia32_rcp28pd_mask:
3395 case X86::BI__builtin_ia32_rcp28ps_mask:
3396 case X86::BI__builtin_ia32_rsqrt28pd_mask:
3397 case X86::BI__builtin_ia32_rsqrt28ps_mask:
3398 case X86::BI__builtin_ia32_vcomisd:
3399 case X86::BI__builtin_ia32_vcomiss:
3400 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3401 ArgNum = 3;
3402 break;
3403 case X86::BI__builtin_ia32_cmppd512_mask:
3404 case X86::BI__builtin_ia32_cmpps512_mask:
3405 case X86::BI__builtin_ia32_cmpsd_mask:
3406 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003407 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003408 case X86::BI__builtin_ia32_getexpsd128_round_mask:
3409 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper902f6492019-05-28 23:26:22 +00003410 case X86::BI__builtin_ia32_getmantpd512_mask:
3411 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003412 case X86::BI__builtin_ia32_maxsd_round_mask:
3413 case X86::BI__builtin_ia32_maxss_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003414 case X86::BI__builtin_ia32_minsd_round_mask:
3415 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003416 case X86::BI__builtin_ia32_rcp28sd_round_mask:
3417 case X86::BI__builtin_ia32_rcp28ss_round_mask:
3418 case X86::BI__builtin_ia32_reducepd512_mask:
3419 case X86::BI__builtin_ia32_reduceps512_mask:
3420 case X86::BI__builtin_ia32_rndscalepd_mask:
3421 case X86::BI__builtin_ia32_rndscaleps_mask:
3422 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3423 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3424 ArgNum = 4;
3425 break;
3426 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003427 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003428 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003429 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003430 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003431 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003432 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003433 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Topper902f6492019-05-28 23:26:22 +00003434 case X86::BI__builtin_ia32_getmantsd_round_mask:
3435 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003436 case X86::BI__builtin_ia32_rangepd512_mask:
3437 case X86::BI__builtin_ia32_rangeps512_mask:
3438 case X86::BI__builtin_ia32_rangesd128_round_mask:
3439 case X86::BI__builtin_ia32_rangess128_round_mask:
3440 case X86::BI__builtin_ia32_reducesd_mask:
3441 case X86::BI__builtin_ia32_reducess_mask:
3442 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3443 case X86::BI__builtin_ia32_rndscaless_round_mask:
3444 ArgNum = 5;
3445 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003446 case X86::BI__builtin_ia32_vcvtsd2si64:
3447 case X86::BI__builtin_ia32_vcvtsd2si32:
3448 case X86::BI__builtin_ia32_vcvtsd2usi32:
3449 case X86::BI__builtin_ia32_vcvtsd2usi64:
3450 case X86::BI__builtin_ia32_vcvtss2si32:
3451 case X86::BI__builtin_ia32_vcvtss2si64:
3452 case X86::BI__builtin_ia32_vcvtss2usi32:
3453 case X86::BI__builtin_ia32_vcvtss2usi64:
Craig Topper8bf793f2018-06-29 05:43:33 +00003454 case X86::BI__builtin_ia32_sqrtpd512:
3455 case X86::BI__builtin_ia32_sqrtps512:
Craig Topper7609f1c2016-10-01 21:03:50 +00003456 ArgNum = 1;
3457 HasRC = true;
3458 break;
Craig Topper3614b412018-06-10 06:01:42 +00003459 case X86::BI__builtin_ia32_addpd512:
3460 case X86::BI__builtin_ia32_addps512:
3461 case X86::BI__builtin_ia32_divpd512:
3462 case X86::BI__builtin_ia32_divps512:
3463 case X86::BI__builtin_ia32_mulpd512:
3464 case X86::BI__builtin_ia32_mulps512:
3465 case X86::BI__builtin_ia32_subpd512:
3466 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00003467 case X86::BI__builtin_ia32_cvtsi2sd64:
3468 case X86::BI__builtin_ia32_cvtsi2ss32:
3469 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00003470 case X86::BI__builtin_ia32_cvtusi2sd64:
3471 case X86::BI__builtin_ia32_cvtusi2ss32:
3472 case X86::BI__builtin_ia32_cvtusi2ss64:
3473 ArgNum = 2;
3474 HasRC = true;
3475 break;
3476 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3477 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3478 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003479 case X86::BI__builtin_ia32_cvtpd2dq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003480 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003481 case X86::BI__builtin_ia32_cvtpd2udq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003482 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003483 case X86::BI__builtin_ia32_cvtps2dq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003484 case X86::BI__builtin_ia32_cvtps2qq512_mask:
Craig Topper1b62c752019-04-08 17:05:57 +00003485 case X86::BI__builtin_ia32_cvtps2udq512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003486 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3487 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3488 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3489 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3490 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3491 ArgNum = 3;
3492 HasRC = true;
3493 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003494 case X86::BI__builtin_ia32_addss_round_mask:
3495 case X86::BI__builtin_ia32_addsd_round_mask:
3496 case X86::BI__builtin_ia32_divss_round_mask:
3497 case X86::BI__builtin_ia32_divsd_round_mask:
3498 case X86::BI__builtin_ia32_mulss_round_mask:
3499 case X86::BI__builtin_ia32_mulsd_round_mask:
3500 case X86::BI__builtin_ia32_subss_round_mask:
3501 case X86::BI__builtin_ia32_subsd_round_mask:
3502 case X86::BI__builtin_ia32_scalefpd512_mask:
3503 case X86::BI__builtin_ia32_scalefps512_mask:
3504 case X86::BI__builtin_ia32_scalefsd_round_mask:
3505 case X86::BI__builtin_ia32_scalefss_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003506 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3507 case X86::BI__builtin_ia32_sqrtsd_round_mask:
3508 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003509 case X86::BI__builtin_ia32_vfmaddsd3_mask:
3510 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3511 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3512 case X86::BI__builtin_ia32_vfmaddss3_mask:
3513 case X86::BI__builtin_ia32_vfmaddss3_maskz:
3514 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00003515 case X86::BI__builtin_ia32_vfmaddpd512_mask:
3516 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3517 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3518 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3519 case X86::BI__builtin_ia32_vfmaddps512_mask:
3520 case X86::BI__builtin_ia32_vfmaddps512_maskz:
3521 case X86::BI__builtin_ia32_vfmaddps512_mask3:
3522 case X86::BI__builtin_ia32_vfmsubps512_mask3:
3523 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3524 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3525 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3526 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3527 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3528 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3529 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3530 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00003531 ArgNum = 4;
3532 HasRC = true;
3533 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003534 }
3535
3536 llvm::APSInt Result;
3537
3538 // We can't check the value of a dependent argument.
3539 Expr *Arg = TheCall->getArg(ArgNum);
3540 if (Arg->isTypeDependent() || Arg->isValueDependent())
3541 return false;
3542
3543 // Check constant-ness first.
3544 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3545 return true;
3546
3547 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3548 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
Craig Topperce2cb0f2019-09-09 17:48:05 +00003549 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3550 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
Craig Toppera7e253e2016-09-23 04:48:31 +00003551 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3552 Result == 8/*ROUND_NO_EXC*/ ||
Craig Topperce2cb0f2019-09-09 17:48:05 +00003553 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
Craig Toppera7e253e2016-09-23 04:48:31 +00003554 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3555 return false;
3556
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003557 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3558 << Arg->getSourceRange();
Craig Toppera7e253e2016-09-23 04:48:31 +00003559}
3560
Craig Topperdf5beb22017-03-13 17:16:50 +00003561// Check if the gather/scatter scale is legal.
3562bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3563 CallExpr *TheCall) {
3564 unsigned ArgNum = 0;
3565 switch (BuiltinID) {
3566 default:
3567 return false;
3568 case X86::BI__builtin_ia32_gatherpfdpd:
3569 case X86::BI__builtin_ia32_gatherpfdps:
3570 case X86::BI__builtin_ia32_gatherpfqpd:
3571 case X86::BI__builtin_ia32_gatherpfqps:
3572 case X86::BI__builtin_ia32_scatterpfdpd:
3573 case X86::BI__builtin_ia32_scatterpfdps:
3574 case X86::BI__builtin_ia32_scatterpfqpd:
3575 case X86::BI__builtin_ia32_scatterpfqps:
3576 ArgNum = 3;
3577 break;
3578 case X86::BI__builtin_ia32_gatherd_pd:
3579 case X86::BI__builtin_ia32_gatherd_pd256:
3580 case X86::BI__builtin_ia32_gatherq_pd:
3581 case X86::BI__builtin_ia32_gatherq_pd256:
3582 case X86::BI__builtin_ia32_gatherd_ps:
3583 case X86::BI__builtin_ia32_gatherd_ps256:
3584 case X86::BI__builtin_ia32_gatherq_ps:
3585 case X86::BI__builtin_ia32_gatherq_ps256:
3586 case X86::BI__builtin_ia32_gatherd_q:
3587 case X86::BI__builtin_ia32_gatherd_q256:
3588 case X86::BI__builtin_ia32_gatherq_q:
3589 case X86::BI__builtin_ia32_gatherq_q256:
3590 case X86::BI__builtin_ia32_gatherd_d:
3591 case X86::BI__builtin_ia32_gatherd_d256:
3592 case X86::BI__builtin_ia32_gatherq_d:
3593 case X86::BI__builtin_ia32_gatherq_d256:
3594 case X86::BI__builtin_ia32_gather3div2df:
3595 case X86::BI__builtin_ia32_gather3div2di:
3596 case X86::BI__builtin_ia32_gather3div4df:
3597 case X86::BI__builtin_ia32_gather3div4di:
3598 case X86::BI__builtin_ia32_gather3div4sf:
3599 case X86::BI__builtin_ia32_gather3div4si:
3600 case X86::BI__builtin_ia32_gather3div8sf:
3601 case X86::BI__builtin_ia32_gather3div8si:
3602 case X86::BI__builtin_ia32_gather3siv2df:
3603 case X86::BI__builtin_ia32_gather3siv2di:
3604 case X86::BI__builtin_ia32_gather3siv4df:
3605 case X86::BI__builtin_ia32_gather3siv4di:
3606 case X86::BI__builtin_ia32_gather3siv4sf:
3607 case X86::BI__builtin_ia32_gather3siv4si:
3608 case X86::BI__builtin_ia32_gather3siv8sf:
3609 case X86::BI__builtin_ia32_gather3siv8si:
3610 case X86::BI__builtin_ia32_gathersiv8df:
3611 case X86::BI__builtin_ia32_gathersiv16sf:
3612 case X86::BI__builtin_ia32_gatherdiv8df:
3613 case X86::BI__builtin_ia32_gatherdiv16sf:
3614 case X86::BI__builtin_ia32_gathersiv8di:
3615 case X86::BI__builtin_ia32_gathersiv16si:
3616 case X86::BI__builtin_ia32_gatherdiv8di:
3617 case X86::BI__builtin_ia32_gatherdiv16si:
3618 case X86::BI__builtin_ia32_scatterdiv2df:
3619 case X86::BI__builtin_ia32_scatterdiv2di:
3620 case X86::BI__builtin_ia32_scatterdiv4df:
3621 case X86::BI__builtin_ia32_scatterdiv4di:
3622 case X86::BI__builtin_ia32_scatterdiv4sf:
3623 case X86::BI__builtin_ia32_scatterdiv4si:
3624 case X86::BI__builtin_ia32_scatterdiv8sf:
3625 case X86::BI__builtin_ia32_scatterdiv8si:
3626 case X86::BI__builtin_ia32_scattersiv2df:
3627 case X86::BI__builtin_ia32_scattersiv2di:
3628 case X86::BI__builtin_ia32_scattersiv4df:
3629 case X86::BI__builtin_ia32_scattersiv4di:
3630 case X86::BI__builtin_ia32_scattersiv4sf:
3631 case X86::BI__builtin_ia32_scattersiv4si:
3632 case X86::BI__builtin_ia32_scattersiv8sf:
3633 case X86::BI__builtin_ia32_scattersiv8si:
3634 case X86::BI__builtin_ia32_scattersiv8df:
3635 case X86::BI__builtin_ia32_scattersiv16sf:
3636 case X86::BI__builtin_ia32_scatterdiv8df:
3637 case X86::BI__builtin_ia32_scatterdiv16sf:
3638 case X86::BI__builtin_ia32_scattersiv8di:
3639 case X86::BI__builtin_ia32_scattersiv16si:
3640 case X86::BI__builtin_ia32_scatterdiv8di:
3641 case X86::BI__builtin_ia32_scatterdiv16si:
3642 ArgNum = 4;
3643 break;
3644 }
3645
3646 llvm::APSInt Result;
3647
3648 // We can't check the value of a dependent argument.
3649 Expr *Arg = TheCall->getArg(ArgNum);
3650 if (Arg->isTypeDependent() || Arg->isValueDependent())
3651 return false;
3652
3653 // Check constant-ness first.
3654 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3655 return true;
3656
3657 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3658 return false;
3659
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003660 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3661 << Arg->getSourceRange();
Craig Topperdf5beb22017-03-13 17:16:50 +00003662}
3663
Craig Topper51738f82018-04-26 20:14:46 +00003664static bool isX86_32Builtin(unsigned BuiltinID) {
3665 // These builtins only work on x86-32 targets.
3666 switch (BuiltinID) {
3667 case X86::BI__builtin_ia32_readeflags_u32:
3668 case X86::BI__builtin_ia32_writeeflags_u32:
3669 return true;
3670 }
3671
3672 return false;
3673}
3674
Craig Topperf0ddc892016-09-23 04:48:27 +00003675bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3676 if (BuiltinID == X86::BI__builtin_cpu_supports)
3677 return SemaBuiltinCpuSupports(*this, TheCall);
3678
Craig Topper699ae0c2017-08-10 20:28:30 +00003679 if (BuiltinID == X86::BI__builtin_cpu_is)
3680 return SemaBuiltinCpuIs(*this, TheCall);
3681
Craig Topper51738f82018-04-26 20:14:46 +00003682 // Check for 32-bit only builtins on a 64-bit target.
3683 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3684 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003685 return Diag(TheCall->getCallee()->getBeginLoc(),
Craig Topper51738f82018-04-26 20:14:46 +00003686 diag::err_32_bit_builtin_64_bit_tgt);
3687
Craig Toppera7e253e2016-09-23 04:48:31 +00003688 // If the intrinsic has rounding or SAE make sure its valid.
3689 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3690 return true;
3691
Craig Topperdf5beb22017-03-13 17:16:50 +00003692 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3693 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3694 return true;
3695
Craig Topperf0ddc892016-09-23 04:48:27 +00003696 // For intrinsics which take an immediate value as part of the instruction,
3697 // range check them here.
3698 int i = 0, l = 0, u = 0;
3699 switch (BuiltinID) {
3700 default:
3701 return false;
Craig Topper11899b02018-06-05 21:54:35 +00003702 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00003703 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003704 case X86::BI__builtin_ia32_vextractf128_pd256:
3705 case X86::BI__builtin_ia32_vextractf128_ps256:
3706 case X86::BI__builtin_ia32_vextractf128_si256:
3707 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00003708 case X86::BI__builtin_ia32_extractf64x4_mask:
3709 case X86::BI__builtin_ia32_extracti64x4_mask:
3710 case X86::BI__builtin_ia32_extractf32x8_mask:
3711 case X86::BI__builtin_ia32_extracti32x8_mask:
3712 case X86::BI__builtin_ia32_extractf64x2_256_mask:
3713 case X86::BI__builtin_ia32_extracti64x2_256_mask:
3714 case X86::BI__builtin_ia32_extractf32x4_256_mask:
3715 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003716 i = 1; l = 0; u = 1;
3717 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003718 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003719 case X86::BI__builtin_ia32_vinsertf128_pd256:
3720 case X86::BI__builtin_ia32_vinsertf128_ps256:
3721 case X86::BI__builtin_ia32_vinsertf128_si256:
3722 case X86::BI__builtin_ia32_insert128i256:
3723 case X86::BI__builtin_ia32_insertf32x8:
3724 case X86::BI__builtin_ia32_inserti32x8:
3725 case X86::BI__builtin_ia32_insertf64x4:
3726 case X86::BI__builtin_ia32_inserti64x4:
3727 case X86::BI__builtin_ia32_insertf64x2_256:
3728 case X86::BI__builtin_ia32_inserti64x2_256:
3729 case X86::BI__builtin_ia32_insertf32x4_256:
3730 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00003731 i = 2; l = 0; u = 1;
3732 break;
Craig Topperacf56012018-06-08 00:59:27 +00003733 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00003734 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003735 case X86::BI__builtin_ia32_vec_ext_v4si:
3736 case X86::BI__builtin_ia32_vec_ext_v4sf:
3737 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00003738 case X86::BI__builtin_ia32_extractf32x4_mask:
3739 case X86::BI__builtin_ia32_extracti32x4_mask:
3740 case X86::BI__builtin_ia32_extractf64x2_512_mask:
3741 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003742 i = 1; l = 0; u = 3;
3743 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003744 case X86::BI_mm_prefetch:
3745 case X86::BI__builtin_ia32_vec_ext_v8hi:
3746 case X86::BI__builtin_ia32_vec_ext_v8si:
3747 i = 1; l = 0; u = 7;
3748 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00003749 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00003750 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00003751 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00003752 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003753 case X86::BI__builtin_ia32_vec_set_v4si:
3754 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00003755 case X86::BI__builtin_ia32_shuf_f32x4_256:
3756 case X86::BI__builtin_ia32_shuf_f64x2_256:
3757 case X86::BI__builtin_ia32_shuf_i32x4_256:
3758 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00003759 case X86::BI__builtin_ia32_insertf64x2_512:
3760 case X86::BI__builtin_ia32_inserti64x2_512:
3761 case X86::BI__builtin_ia32_insertf32x4:
3762 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00003763 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003764 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00003765 case X86::BI__builtin_ia32_vpermil2pd:
3766 case X86::BI__builtin_ia32_vpermil2pd256:
3767 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00003768 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00003769 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003770 break;
Craig Topper95b0d732015-01-25 23:30:05 +00003771 case X86::BI__builtin_ia32_cmpb128_mask:
3772 case X86::BI__builtin_ia32_cmpw128_mask:
3773 case X86::BI__builtin_ia32_cmpd128_mask:
3774 case X86::BI__builtin_ia32_cmpq128_mask:
3775 case X86::BI__builtin_ia32_cmpb256_mask:
3776 case X86::BI__builtin_ia32_cmpw256_mask:
3777 case X86::BI__builtin_ia32_cmpd256_mask:
3778 case X86::BI__builtin_ia32_cmpq256_mask:
3779 case X86::BI__builtin_ia32_cmpb512_mask:
3780 case X86::BI__builtin_ia32_cmpw512_mask:
3781 case X86::BI__builtin_ia32_cmpd512_mask:
3782 case X86::BI__builtin_ia32_cmpq512_mask:
3783 case X86::BI__builtin_ia32_ucmpb128_mask:
3784 case X86::BI__builtin_ia32_ucmpw128_mask:
3785 case X86::BI__builtin_ia32_ucmpd128_mask:
3786 case X86::BI__builtin_ia32_ucmpq128_mask:
3787 case X86::BI__builtin_ia32_ucmpb256_mask:
3788 case X86::BI__builtin_ia32_ucmpw256_mask:
3789 case X86::BI__builtin_ia32_ucmpd256_mask:
3790 case X86::BI__builtin_ia32_ucmpq256_mask:
3791 case X86::BI__builtin_ia32_ucmpb512_mask:
3792 case X86::BI__builtin_ia32_ucmpw512_mask:
3793 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00003794 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00003795 case X86::BI__builtin_ia32_vpcomub:
3796 case X86::BI__builtin_ia32_vpcomuw:
3797 case X86::BI__builtin_ia32_vpcomud:
3798 case X86::BI__builtin_ia32_vpcomuq:
3799 case X86::BI__builtin_ia32_vpcomb:
3800 case X86::BI__builtin_ia32_vpcomw:
3801 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00003802 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00003803 case X86::BI__builtin_ia32_vec_set_v8hi:
3804 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00003805 i = 2; l = 0; u = 7;
3806 break;
Craig Topperacf56012018-06-08 00:59:27 +00003807 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003808 case X86::BI__builtin_ia32_roundps:
3809 case X86::BI__builtin_ia32_roundpd:
3810 case X86::BI__builtin_ia32_roundps256:
3811 case X86::BI__builtin_ia32_roundpd256:
Craig Topper03a1d482018-06-15 17:03:32 +00003812 case X86::BI__builtin_ia32_getmantpd128_mask:
3813 case X86::BI__builtin_ia32_getmantpd256_mask:
3814 case X86::BI__builtin_ia32_getmantps128_mask:
3815 case X86::BI__builtin_ia32_getmantps256_mask:
3816 case X86::BI__builtin_ia32_getmantpd512_mask:
3817 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003818 case X86::BI__builtin_ia32_vec_ext_v16qi:
3819 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003820 i = 1; l = 0; u = 15;
3821 break;
Craig Topper7d17d722018-06-08 00:00:21 +00003822 case X86::BI__builtin_ia32_pblendd128:
3823 case X86::BI__builtin_ia32_blendps:
3824 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00003825 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003826 case X86::BI__builtin_ia32_roundss:
3827 case X86::BI__builtin_ia32_roundsd:
3828 case X86::BI__builtin_ia32_rangepd128_mask:
3829 case X86::BI__builtin_ia32_rangepd256_mask:
3830 case X86::BI__builtin_ia32_rangepd512_mask:
3831 case X86::BI__builtin_ia32_rangeps128_mask:
3832 case X86::BI__builtin_ia32_rangeps256_mask:
3833 case X86::BI__builtin_ia32_rangeps512_mask:
3834 case X86::BI__builtin_ia32_getmantsd_round_mask:
3835 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003836 case X86::BI__builtin_ia32_vec_set_v16qi:
3837 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003838 i = 2; l = 0; u = 15;
3839 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003840 case X86::BI__builtin_ia32_vec_ext_v32qi:
3841 i = 1; l = 0; u = 31;
3842 break;
Craig Topper39c87102016-05-18 03:18:12 +00003843 case X86::BI__builtin_ia32_cmpps:
3844 case X86::BI__builtin_ia32_cmpss:
3845 case X86::BI__builtin_ia32_cmppd:
3846 case X86::BI__builtin_ia32_cmpsd:
3847 case X86::BI__builtin_ia32_cmpps256:
3848 case X86::BI__builtin_ia32_cmppd256:
3849 case X86::BI__builtin_ia32_cmpps128_mask:
3850 case X86::BI__builtin_ia32_cmppd128_mask:
3851 case X86::BI__builtin_ia32_cmpps256_mask:
3852 case X86::BI__builtin_ia32_cmppd256_mask:
3853 case X86::BI__builtin_ia32_cmpps512_mask:
3854 case X86::BI__builtin_ia32_cmppd512_mask:
3855 case X86::BI__builtin_ia32_cmpsd_mask:
3856 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003857 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00003858 i = 2; l = 0; u = 31;
3859 break;
Craig Topper03f4f042018-06-08 18:00:25 +00003860 case X86::BI__builtin_ia32_permdf256:
3861 case X86::BI__builtin_ia32_permdi256:
3862 case X86::BI__builtin_ia32_permdf512:
3863 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00003864 case X86::BI__builtin_ia32_vpermilps:
3865 case X86::BI__builtin_ia32_vpermilps256:
3866 case X86::BI__builtin_ia32_vpermilpd512:
3867 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00003868 case X86::BI__builtin_ia32_pshufd:
3869 case X86::BI__builtin_ia32_pshufd256:
3870 case X86::BI__builtin_ia32_pshufd512:
3871 case X86::BI__builtin_ia32_pshufhw:
3872 case X86::BI__builtin_ia32_pshufhw256:
3873 case X86::BI__builtin_ia32_pshufhw512:
3874 case X86::BI__builtin_ia32_pshuflw:
3875 case X86::BI__builtin_ia32_pshuflw256:
3876 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00003877 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00003878 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003879 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00003880 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3881 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003882 case X86::BI__builtin_ia32_rndscaleps_128_mask:
3883 case X86::BI__builtin_ia32_rndscalepd_128_mask:
3884 case X86::BI__builtin_ia32_rndscaleps_256_mask:
3885 case X86::BI__builtin_ia32_rndscalepd_256_mask:
3886 case X86::BI__builtin_ia32_rndscaleps_mask:
3887 case X86::BI__builtin_ia32_rndscalepd_mask:
3888 case X86::BI__builtin_ia32_reducepd128_mask:
3889 case X86::BI__builtin_ia32_reducepd256_mask:
3890 case X86::BI__builtin_ia32_reducepd512_mask:
3891 case X86::BI__builtin_ia32_reduceps128_mask:
3892 case X86::BI__builtin_ia32_reduceps256_mask:
3893 case X86::BI__builtin_ia32_reduceps512_mask:
Craig Topper0e9de762018-06-30 01:32:14 +00003894 case X86::BI__builtin_ia32_prold512:
3895 case X86::BI__builtin_ia32_prolq512:
3896 case X86::BI__builtin_ia32_prold128:
3897 case X86::BI__builtin_ia32_prold256:
3898 case X86::BI__builtin_ia32_prolq128:
3899 case X86::BI__builtin_ia32_prolq256:
3900 case X86::BI__builtin_ia32_prord512:
3901 case X86::BI__builtin_ia32_prorq512:
3902 case X86::BI__builtin_ia32_prord128:
3903 case X86::BI__builtin_ia32_prord256:
3904 case X86::BI__builtin_ia32_prorq128:
3905 case X86::BI__builtin_ia32_prorq256:
Craig Topper39c87102016-05-18 03:18:12 +00003906 case X86::BI__builtin_ia32_fpclasspd128_mask:
3907 case X86::BI__builtin_ia32_fpclasspd256_mask:
3908 case X86::BI__builtin_ia32_fpclassps128_mask:
3909 case X86::BI__builtin_ia32_fpclassps256_mask:
3910 case X86::BI__builtin_ia32_fpclassps512_mask:
3911 case X86::BI__builtin_ia32_fpclasspd512_mask:
3912 case X86::BI__builtin_ia32_fpclasssd_mask:
3913 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00003914 case X86::BI__builtin_ia32_pslldqi128_byteshift:
3915 case X86::BI__builtin_ia32_pslldqi256_byteshift:
3916 case X86::BI__builtin_ia32_pslldqi512_byteshift:
3917 case X86::BI__builtin_ia32_psrldqi128_byteshift:
3918 case X86::BI__builtin_ia32_psrldqi256_byteshift:
3919 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper2aa8efc2018-08-31 18:22:52 +00003920 case X86::BI__builtin_ia32_kshiftliqi:
3921 case X86::BI__builtin_ia32_kshiftlihi:
3922 case X86::BI__builtin_ia32_kshiftlisi:
3923 case X86::BI__builtin_ia32_kshiftlidi:
3924 case X86::BI__builtin_ia32_kshiftriqi:
3925 case X86::BI__builtin_ia32_kshiftrihi:
3926 case X86::BI__builtin_ia32_kshiftrisi:
3927 case X86::BI__builtin_ia32_kshiftridi:
Craig Topper39c87102016-05-18 03:18:12 +00003928 i = 1; l = 0; u = 255;
3929 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00003930 case X86::BI__builtin_ia32_vperm2f128_pd256:
3931 case X86::BI__builtin_ia32_vperm2f128_ps256:
3932 case X86::BI__builtin_ia32_vperm2f128_si256:
3933 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00003934 case X86::BI__builtin_ia32_pblendw128:
3935 case X86::BI__builtin_ia32_pblendw256:
3936 case X86::BI__builtin_ia32_blendps256:
3937 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00003938 case X86::BI__builtin_ia32_palignr128:
3939 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00003940 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00003941 case X86::BI__builtin_ia32_alignq512:
3942 case X86::BI__builtin_ia32_alignd512:
3943 case X86::BI__builtin_ia32_alignd128:
3944 case X86::BI__builtin_ia32_alignd256:
3945 case X86::BI__builtin_ia32_alignq128:
3946 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00003947 case X86::BI__builtin_ia32_vcomisd:
3948 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00003949 case X86::BI__builtin_ia32_shuf_f32x4:
3950 case X86::BI__builtin_ia32_shuf_f64x2:
3951 case X86::BI__builtin_ia32_shuf_i32x4:
3952 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00003953 case X86::BI__builtin_ia32_shufpd512:
3954 case X86::BI__builtin_ia32_shufps:
3955 case X86::BI__builtin_ia32_shufps256:
3956 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00003957 case X86::BI__builtin_ia32_dbpsadbw128:
3958 case X86::BI__builtin_ia32_dbpsadbw256:
3959 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00003960 case X86::BI__builtin_ia32_vpshldd128:
3961 case X86::BI__builtin_ia32_vpshldd256:
3962 case X86::BI__builtin_ia32_vpshldd512:
3963 case X86::BI__builtin_ia32_vpshldq128:
3964 case X86::BI__builtin_ia32_vpshldq256:
3965 case X86::BI__builtin_ia32_vpshldq512:
3966 case X86::BI__builtin_ia32_vpshldw128:
3967 case X86::BI__builtin_ia32_vpshldw256:
3968 case X86::BI__builtin_ia32_vpshldw512:
3969 case X86::BI__builtin_ia32_vpshrdd128:
3970 case X86::BI__builtin_ia32_vpshrdd256:
3971 case X86::BI__builtin_ia32_vpshrdd512:
3972 case X86::BI__builtin_ia32_vpshrdq128:
3973 case X86::BI__builtin_ia32_vpshrdq256:
3974 case X86::BI__builtin_ia32_vpshrdq512:
3975 case X86::BI__builtin_ia32_vpshrdw128:
3976 case X86::BI__builtin_ia32_vpshrdw256:
3977 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00003978 i = 2; l = 0; u = 255;
3979 break;
3980 case X86::BI__builtin_ia32_fixupimmpd512_mask:
3981 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3982 case X86::BI__builtin_ia32_fixupimmps512_mask:
3983 case X86::BI__builtin_ia32_fixupimmps512_maskz:
3984 case X86::BI__builtin_ia32_fixupimmsd_mask:
3985 case X86::BI__builtin_ia32_fixupimmsd_maskz:
3986 case X86::BI__builtin_ia32_fixupimmss_mask:
3987 case X86::BI__builtin_ia32_fixupimmss_maskz:
3988 case X86::BI__builtin_ia32_fixupimmpd128_mask:
3989 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3990 case X86::BI__builtin_ia32_fixupimmpd256_mask:
3991 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3992 case X86::BI__builtin_ia32_fixupimmps128_mask:
3993 case X86::BI__builtin_ia32_fixupimmps128_maskz:
3994 case X86::BI__builtin_ia32_fixupimmps256_mask:
3995 case X86::BI__builtin_ia32_fixupimmps256_maskz:
3996 case X86::BI__builtin_ia32_pternlogd512_mask:
3997 case X86::BI__builtin_ia32_pternlogd512_maskz:
3998 case X86::BI__builtin_ia32_pternlogq512_mask:
3999 case X86::BI__builtin_ia32_pternlogq512_maskz:
4000 case X86::BI__builtin_ia32_pternlogd128_mask:
4001 case X86::BI__builtin_ia32_pternlogd128_maskz:
4002 case X86::BI__builtin_ia32_pternlogd256_mask:
4003 case X86::BI__builtin_ia32_pternlogd256_maskz:
4004 case X86::BI__builtin_ia32_pternlogq128_mask:
4005 case X86::BI__builtin_ia32_pternlogq128_maskz:
4006 case X86::BI__builtin_ia32_pternlogq256_mask:
4007 case X86::BI__builtin_ia32_pternlogq256_maskz:
4008 i = 3; l = 0; u = 255;
4009 break;
Craig Topper9625db02017-03-12 22:19:10 +00004010 case X86::BI__builtin_ia32_gatherpfdpd:
4011 case X86::BI__builtin_ia32_gatherpfdps:
4012 case X86::BI__builtin_ia32_gatherpfqpd:
4013 case X86::BI__builtin_ia32_gatherpfqps:
4014 case X86::BI__builtin_ia32_scatterpfdpd:
4015 case X86::BI__builtin_ia32_scatterpfdps:
4016 case X86::BI__builtin_ia32_scatterpfqpd:
4017 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00004018 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00004019 break;
Craig Topper9967a6c2019-06-14 23:23:19 +00004020 case X86::BI__builtin_ia32_reducesd_mask:
4021 case X86::BI__builtin_ia32_reducess_mask:
Craig Topper39c87102016-05-18 03:18:12 +00004022 case X86::BI__builtin_ia32_rndscalesd_round_mask:
4023 case X86::BI__builtin_ia32_rndscaless_round_mask:
4024 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00004025 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004026 }
Chandler Carruth16e6bc22018-06-21 23:46:09 +00004027
4028 // Note that we don't force a hard error on the range check here, allowing
4029 // template-generated or macro-generated dead code to potentially have out-of-
4030 // range values. These need to code generate, but don't need to necessarily
4031 // make any sense. We use a warning that defaults to an error.
4032 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004033}
4034
Richard Smith55ce3522012-06-25 20:30:08 +00004035/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4036/// parameter with the FormatAttr's correct format_idx and firstDataArg.
4037/// Returns true when the format fits the function and the FormatStringInfo has
4038/// been populated.
4039bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4040 FormatStringInfo *FSI) {
4041 FSI->HasVAListArg = Format->getFirstArg() == 0;
4042 FSI->FormatIdx = Format->getFormatIdx() - 1;
4043 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004044
Richard Smith55ce3522012-06-25 20:30:08 +00004045 // The way the format attribute works in GCC, the implicit this argument
4046 // of member functions is counted. However, it doesn't appear in our own
4047 // lists, so decrement format_idx in that case.
4048 if (IsCXXMember) {
4049 if(FSI->FormatIdx == 0)
4050 return false;
4051 --FSI->FormatIdx;
4052 if (FSI->FirstDataArg != 0)
4053 --FSI->FirstDataArg;
4054 }
4055 return true;
4056}
Mike Stump11289f42009-09-09 15:08:12 +00004057
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004058/// Checks if a the given expression evaluates to null.
4059///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004060/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00004061static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004062 // If the expression has non-null type, it doesn't evaluate to null.
4063 if (auto nullability
4064 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4065 if (*nullability == NullabilityKind::NonNull)
4066 return false;
4067 }
4068
Ted Kremeneka146db32014-01-17 06:24:47 +00004069 // As a special case, transparent unions initialized with zero are
4070 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004071 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00004072 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4073 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004074 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00004075 if (const InitListExpr *ILE =
4076 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004077 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00004078 }
4079
4080 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00004081 return (!Expr->isValueDependent() &&
4082 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4083 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004084}
4085
4086static void CheckNonNullArgument(Sema &S,
4087 const Expr *ArgExpr,
4088 SourceLocation CallSiteLoc) {
4089 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00004090 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00004091 S.PDiag(diag::warn_null_arg)
4092 << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00004093}
4094
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004095bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4096 FormatStringInfo FSI;
4097 if ((GetFormatStringType(Format) == FST_NSString) &&
4098 getFormatStringInfo(Format, false, &FSI)) {
4099 Idx = FSI.FormatIdx;
4100 return true;
4101 }
4102 return false;
4103}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004105/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004106/// as formatting string to formatting method.
4107static void
4108DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4109 const NamedDecl *FDecl,
4110 Expr **Args,
4111 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004112 unsigned Idx = 0;
4113 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004114 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4115 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004116 Idx = 2;
4117 Format = true;
4118 }
4119 else
4120 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4121 if (S.GetFormatNSStringIdx(I, Idx)) {
4122 Format = true;
4123 break;
4124 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004125 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004126 if (!Format || NumArgs <= Idx)
4127 return;
4128 const Expr *FormatExpr = Args[Idx];
4129 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4130 FormatExpr = CSCE->getSubExpr();
4131 const StringLiteral *FormatString;
4132 if (const ObjCStringLiteral *OSL =
4133 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4134 FormatString = OSL->getString();
4135 else
4136 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4137 if (!FormatString)
4138 return;
4139 if (S.FormatStringHasSArg(FormatString)) {
4140 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4141 << "%s" << 1 << 1;
4142 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4143 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004144 }
4145}
4146
Douglas Gregorb4866e82015-06-19 18:13:19 +00004147/// Determine whether the given type has a non-null nullability annotation.
4148static bool isNonNullType(ASTContext &ctx, QualType type) {
4149 if (auto nullability = type->getNullability(ctx))
4150 return *nullability == NullabilityKind::NonNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00004151
Douglas Gregorb4866e82015-06-19 18:13:19 +00004152 return false;
4153}
4154
Ted Kremenek2bc73332014-01-17 06:24:43 +00004155static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00004156 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004157 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00004158 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00004159 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004160 assert((FDecl || Proto) && "Need a function declaration or prototype");
4161
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00004162 // Already checked by by constant evaluator.
4163 if (S.isConstantEvaluated())
4164 return;
Ted Kremenek9aedc152014-01-17 06:24:56 +00004165 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00004166 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00004167 if (FDecl) {
4168 // Handle the nonnull attribute on the function/method declaration itself.
4169 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4170 if (!NonNull->args_size()) {
4171 // Easy case: all pointer arguments are nonnull.
4172 for (const auto *Arg : Args)
4173 if (S.isValidPointerAttrType(Arg->getType()))
4174 CheckNonNullArgument(S, Arg, CallSiteLoc);
4175 return;
4176 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004177
Joel E. Denny81508102018-03-13 14:51:22 +00004178 for (const ParamIdx &Idx : NonNull->args()) {
4179 unsigned IdxAST = Idx.getASTIndex();
4180 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00004181 continue;
4182 if (NonNullArgs.empty())
4183 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00004184 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004185 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004186 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004187 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004188
Douglas Gregorb4866e82015-06-19 18:13:19 +00004189 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4190 // Handle the nonnull attribute on the parameters of the
4191 // function/method.
4192 ArrayRef<ParmVarDecl*> parms;
4193 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4194 parms = FD->parameters();
4195 else
4196 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
Fangrui Song6907ce22018-07-30 19:24:48 +00004197
Douglas Gregorb4866e82015-06-19 18:13:19 +00004198 unsigned ParamIndex = 0;
4199 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4200 I != E; ++I, ++ParamIndex) {
4201 const ParmVarDecl *PVD = *I;
Fangrui Song6907ce22018-07-30 19:24:48 +00004202 if (PVD->hasAttr<NonNullAttr>() ||
Douglas Gregorb4866e82015-06-19 18:13:19 +00004203 isNonNullType(S.Context, PVD->getType())) {
4204 if (NonNullArgs.empty())
4205 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00004206
Douglas Gregorb4866e82015-06-19 18:13:19 +00004207 NonNullArgs.set(ParamIndex);
4208 }
4209 }
4210 } else {
4211 // If we have a non-function, non-method declaration but no
4212 // function prototype, try to dig out the function prototype.
4213 if (!Proto) {
4214 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4215 QualType type = VD->getType().getNonReferenceType();
4216 if (auto pointerType = type->getAs<PointerType>())
4217 type = pointerType->getPointeeType();
4218 else if (auto blockType = type->getAs<BlockPointerType>())
4219 type = blockType->getPointeeType();
4220 // FIXME: data member pointers?
4221
4222 // Dig out the function prototype, if there is one.
4223 Proto = type->getAs<FunctionProtoType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004224 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00004225 }
4226
4227 // Fill in non-null argument information from the nullability
4228 // information on the parameter types (if we have them).
4229 if (Proto) {
4230 unsigned Index = 0;
4231 for (auto paramType : Proto->getParamTypes()) {
4232 if (isNonNullType(S.Context, paramType)) {
4233 if (NonNullArgs.empty())
4234 NonNullArgs.resize(Args.size());
Fangrui Song6907ce22018-07-30 19:24:48 +00004235
Douglas Gregorb4866e82015-06-19 18:13:19 +00004236 NonNullArgs.set(Index);
4237 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004238
Douglas Gregorb4866e82015-06-19 18:13:19 +00004239 ++Index;
4240 }
4241 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004242 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004243
Douglas Gregorb4866e82015-06-19 18:13:19 +00004244 // Check for non-null arguments.
Fangrui Song6907ce22018-07-30 19:24:48 +00004245 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
Douglas Gregorb4866e82015-06-19 18:13:19 +00004246 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00004247 if (NonNullArgs[ArgIndex])
4248 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004249 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004250}
4251
Richard Smith55ce3522012-06-25 20:30:08 +00004252/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00004253/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4254/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004255void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00004256 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4257 bool IsMemberFunction, SourceLocation Loc,
4258 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00004259 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00004260 if (CurContext->isDependentContext())
4261 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00004262
Ted Kremenekb8176da2010-09-09 04:33:05 +00004263 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00004264 llvm::SmallBitVector CheckedVarArgs;
4265 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004266 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004267 // Only create vector if there are format attributes.
4268 CheckedVarArgs.resize(Args.size());
4269
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004270 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00004271 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004272 }
Richard Smithd7293d72013-08-05 18:49:43 +00004273 }
Richard Smith55ce3522012-06-25 20:30:08 +00004274
4275 // Refuse POD arguments that weren't caught by the format string
4276 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00004277 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4278 if (CallType != VariadicDoesNotApply &&
4279 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004280 unsigned NumParams = Proto ? Proto->getNumParams()
4281 : FDecl && isa<FunctionDecl>(FDecl)
4282 ? cast<FunctionDecl>(FDecl)->getNumParams()
4283 : FDecl && isa<ObjCMethodDecl>(FDecl)
4284 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4285 : 0;
4286
Alp Toker9cacbab2014-01-20 20:26:09 +00004287 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004288 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00004289 if (const Expr *Arg = Args[ArgIdx]) {
4290 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4291 checkVariadicArgument(Arg, CallType);
4292 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004293 }
Richard Smithd7293d72013-08-05 18:49:43 +00004294 }
Mike Stump11289f42009-09-09 15:08:12 +00004295
Douglas Gregorb4866e82015-06-19 18:13:19 +00004296 if (FDecl || Proto) {
4297 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004298
Richard Trieu41bc0992013-06-22 00:20:41 +00004299 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004300 if (FDecl) {
4301 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00004302 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004303 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004304 }
George Burgess IVce6284b2017-01-28 02:19:40 +00004305
4306 if (FD)
4307 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00004308}
4309
4310/// CheckConstructorCall - Check a constructor call for correctness and safety
4311/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004312void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4313 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004314 const FunctionProtoType *Proto,
4315 SourceLocation Loc) {
4316 VariadicCallType CallType =
4317 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00004318 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4319 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00004320}
4321
4322/// CheckFunctionCall - Check a direct function call for various correctness
4323/// and safety properties not strictly enforced by the C type system.
4324bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4325 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004326 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4327 isa<CXXMethodDecl>(FDecl);
4328 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4329 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00004330 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4331 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00004332 Expr** Args = TheCall->getArgs();
4333 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00004334
4335 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00004336 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004337 // If this is a call to a member operator, hide the first argument
4338 // from checkCall.
4339 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00004340 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00004341 ++Args;
4342 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00004343 } else if (IsMemberFunction)
4344 ImplicitThis =
4345 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4346
4347 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00004348 IsMemberFunction, TheCall->getRParenLoc(),
4349 TheCall->getCallee()->getSourceRange(), CallType);
4350
4351 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4352 // None of the checks below are needed for functions that don't have
4353 // simple names (e.g., C++ conversion functions).
4354 if (!FnInfo)
4355 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004356
Richard Trieua7f30b12016-12-06 01:42:28 +00004357 CheckAbsoluteValueFunction(TheCall, FDecl);
4358 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00004359
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004360 if (getLangOpts().ObjC)
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004361 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004362
Anna Zaks22122702012-01-17 00:37:07 +00004363 unsigned CMId = FDecl->getMemoryFunctionKind();
4364 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00004365 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00004366
Anna Zaks201d4892012-01-13 21:52:01 +00004367 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00004368 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00004369 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00004370 else if (CMId == Builtin::BIstrncat)
4371 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00004372 else
Anna Zaks22122702012-01-17 00:37:07 +00004373 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004374
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004375 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00004376}
4377
Fangrui Song6907ce22018-07-30 19:24:48 +00004378bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00004379 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00004380 VariadicCallType CallType =
4381 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004382
George Burgess IVce6284b2017-01-28 02:19:40 +00004383 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4384 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004385 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004386
4387 return false;
4388}
4389
Richard Trieu664c4c62013-06-20 21:03:13 +00004390bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4391 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00004392 QualType Ty;
4393 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004394 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004395 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004396 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004397 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004398 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004399
Douglas Gregorb4866e82015-06-19 18:13:19 +00004400 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4401 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004402 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004403
Richard Trieu664c4c62013-06-20 21:03:13 +00004404 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00004405 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00004406 CallType = VariadicDoesNotApply;
4407 } else if (Ty->isBlockPointerType()) {
4408 CallType = VariadicBlock;
4409 } else { // Ty->isFunctionPointerType()
4410 CallType = VariadicFunction;
4411 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004412
George Burgess IVce6284b2017-01-28 02:19:40 +00004413 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004414 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4415 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00004416 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00004417
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004418 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00004419}
4420
Richard Trieu41bc0992013-06-22 00:20:41 +00004421/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4422/// such as function pointers returned from functions.
4423bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004424 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00004425 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00004426 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00004427 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004428 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00004429 TheCall->getCallee()->getSourceRange(), CallType);
4430
4431 return false;
4432}
4433
Tim Northovere94a34c2014-03-11 10:49:14 +00004434static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00004435 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00004436 return false;
4437
JF Bastiendda2cb12016-04-18 18:01:49 +00004438 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00004439 switch (Op) {
4440 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004441 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00004442 llvm_unreachable("There is no ordering argument for an init");
4443
4444 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004445 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00004446 case AtomicExpr::AO__atomic_load_n:
4447 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00004448 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4449 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004450
4451 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004452 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00004453 case AtomicExpr::AO__atomic_store:
4454 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00004455 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4456 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4457 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004458
4459 default:
4460 return true;
4461 }
4462}
4463
Richard Smithfeea8832012-04-12 05:08:17 +00004464ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4465 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004466 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4467 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004468
Yaxun Liu39195062017-08-04 18:16:31 +00004469 // All the non-OpenCL operations take one of the following forms.
4470 // The OpenCL operations take the __c11 forms with one extra argument for
4471 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00004472 enum {
4473 // C __c11_atomic_init(A *, C)
4474 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004475
Richard Smithfeea8832012-04-12 05:08:17 +00004476 // C __c11_atomic_load(A *, int)
4477 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004478
Richard Smithfeea8832012-04-12 05:08:17 +00004479 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00004480 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004481
Eric Fiselier8d662442016-03-30 23:39:56 +00004482 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00004483 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004484
Richard Smithfeea8832012-04-12 05:08:17 +00004485 // C __c11_atomic_add(A *, M, int)
4486 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004487
Richard Smithfeea8832012-04-12 05:08:17 +00004488 // C __atomic_exchange_n(A *, CP, int)
4489 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004490
Richard Smithfeea8832012-04-12 05:08:17 +00004491 // void __atomic_exchange(A *, C *, CP, int)
4492 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004493
Richard Smithfeea8832012-04-12 05:08:17 +00004494 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4495 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004496
Richard Smithfeea8832012-04-12 05:08:17 +00004497 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4498 GNUCmpXchg
4499 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004500
Yaxun Liu39195062017-08-04 18:16:31 +00004501 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00004502 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4503 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00004504 // where:
4505 // C is an appropriate type,
4506 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4507 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4508 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4509 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004510
Yaxun Liu39195062017-08-04 18:16:31 +00004511 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4512 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4513 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00004514 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4515 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4516 AtomicExpr::AO__atomic_load,
4517 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00004518 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4519 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4520 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4521 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4522 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00004523 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4524 Op == AtomicExpr::AO__atomic_store_n ||
4525 Op == AtomicExpr::AO__atomic_exchange_n ||
4526 Op == AtomicExpr::AO__atomic_compare_exchange_n;
4527 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004528 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00004529
4530 switch (Op) {
4531 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004532 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00004533 Form = Init;
4534 break;
4535
4536 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004537 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004538 case AtomicExpr::AO__atomic_load_n:
4539 Form = Load;
4540 break;
4541
Richard Smithfeea8832012-04-12 05:08:17 +00004542 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00004543 Form = LoadCopy;
4544 break;
4545
4546 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004547 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00004548 case AtomicExpr::AO__atomic_store:
4549 case AtomicExpr::AO__atomic_store_n:
4550 Form = Copy;
4551 break;
4552
4553 case AtomicExpr::AO__c11_atomic_fetch_add:
4554 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00004555 case AtomicExpr::AO__opencl_atomic_fetch_add:
4556 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4557 case AtomicExpr::AO__opencl_atomic_fetch_min:
4558 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004559 case AtomicExpr::AO__atomic_fetch_add:
4560 case AtomicExpr::AO__atomic_fetch_sub:
4561 case AtomicExpr::AO__atomic_add_fetch:
4562 case AtomicExpr::AO__atomic_sub_fetch:
4563 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00004564 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00004565 case AtomicExpr::AO__c11_atomic_fetch_and:
4566 case AtomicExpr::AO__c11_atomic_fetch_or:
4567 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00004568 case AtomicExpr::AO__opencl_atomic_fetch_and:
4569 case AtomicExpr::AO__opencl_atomic_fetch_or:
4570 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00004571 case AtomicExpr::AO__atomic_fetch_and:
4572 case AtomicExpr::AO__atomic_fetch_or:
4573 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004574 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004575 case AtomicExpr::AO__atomic_and_fetch:
4576 case AtomicExpr::AO__atomic_or_fetch:
4577 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004578 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00004579 Form = Arithmetic;
4580 break;
4581
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004582 case AtomicExpr::AO__atomic_fetch_min:
4583 case AtomicExpr::AO__atomic_fetch_max:
4584 IsMinMax = true;
4585 Form = Arithmetic;
4586 break;
4587
Richard Smithfeea8832012-04-12 05:08:17 +00004588 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00004589 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00004590 case AtomicExpr::AO__atomic_exchange_n:
4591 Form = Xchg;
4592 break;
4593
4594 case AtomicExpr::AO__atomic_exchange:
4595 Form = GNUXchg;
4596 break;
4597
4598 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4599 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00004600 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4601 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004602 Form = C11CmpXchg;
4603 break;
4604
4605 case AtomicExpr::AO__atomic_compare_exchange:
4606 case AtomicExpr::AO__atomic_compare_exchange_n:
4607 Form = GNUCmpXchg;
4608 break;
4609 }
4610
Yaxun Liu39195062017-08-04 18:16:31 +00004611 unsigned AdjustedNumArgs = NumArgs[Form];
4612 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4613 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00004614 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00004615 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004616 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4617 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4618 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004619 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00004620 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004621 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004622 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004623 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4624 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004625 return ExprError();
4626 }
4627
Richard Smithfeea8832012-04-12 05:08:17 +00004628 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004629 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00004630 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4631 if (ConvertedPtr.isInvalid())
4632 return ExprError();
4633
4634 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004635 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4636 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004637 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4638 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004639 return ExprError();
4640 }
4641
Richard Smithfeea8832012-04-12 05:08:17 +00004642 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4643 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4644 QualType ValType = AtomTy; // 'C'
4645 if (IsC11) {
4646 if (!AtomTy->isAtomicType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004647 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4648 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004649 return ExprError();
4650 }
JF Bastienb4b1f592018-08-02 17:35:46 +00004651 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
Yaxun Liu39195062017-08-04 18:16:31 +00004652 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004653 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00004654 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4655 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00004656 return ExprError();
4657 }
Richard Smithfeea8832012-04-12 05:08:17 +00004658 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00004659 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004660 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004661 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4662 << Ptr->getType() << Ptr->getSourceRange();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004663 return ExprError();
4664 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004665 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004666
Richard Smithfeea8832012-04-12 05:08:17 +00004667 // For an arithmetic operation, the implied arithmetic must be well-formed.
4668 if (Form == Arithmetic) {
4669 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004670 if (IsAddSub && !ValType->isIntegerType()
4671 && !ValType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004672 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4673 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004674 return ExprError();
4675 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004676 if (IsMinMax) {
4677 const BuiltinType *BT = ValType->getAs<BuiltinType>();
4678 if (!BT || (BT->getKind() != BuiltinType::Int &&
4679 BT->getKind() != BuiltinType::UInt)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004680 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004681 return ExprError();
4682 }
4683 }
4684 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004685 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4686 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004687 return ExprError();
4688 }
David Majnemere85cff82015-01-28 05:48:06 +00004689 if (IsC11 && ValType->isPointerType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004690 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
David Majnemere85cff82015-01-28 05:48:06 +00004691 diag::err_incomplete_type)) {
4692 return ExprError();
4693 }
Richard Smithfeea8832012-04-12 05:08:17 +00004694 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4695 // For __atomic_*_n operations, the value type must be a scalar integral or
4696 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004697 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4698 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004699 return ExprError();
4700 }
4701
Eli Friedmanaa769812013-09-11 03:49:34 +00004702 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4703 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00004704 // For GNU atomics, require a trivially-copyable type. This is not part of
4705 // the GNU atomics specification, but we enforce it for sanity.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004706 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4707 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004708 return ExprError();
4709 }
4710
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004711 switch (ValType.getObjCLifetime()) {
4712 case Qualifiers::OCL_None:
4713 case Qualifiers::OCL_ExplicitNone:
4714 // okay
4715 break;
4716
4717 case Qualifiers::OCL_Weak:
4718 case Qualifiers::OCL_Strong:
4719 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00004720 // FIXME: Can this happen? By this point, ValType should be known
4721 // to be trivially copyable.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004722 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4723 << ValType << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004724 return ExprError();
4725 }
4726
JF Bastien7f0a05a2018-05-25 00:07:09 +00004727 // All atomic operations have an overload which takes a pointer to a volatile
4728 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4729 // into the result or the other operands. Similarly atomic_load takes a
4730 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00004731 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00004732 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004733 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00004734 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4735 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004736 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00004737 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004738 ResultType = Context.BoolTy;
4739
Richard Smithfeea8832012-04-12 05:08:17 +00004740 // The type of a parameter passed 'by value'. In the GNU atomics, such
4741 // arguments are actually passed as pointers.
4742 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00004743 bool IsPassedByAddress = false;
4744 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00004745 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00004746 IsPassedByAddress = true;
4747 }
Richard Smithfeea8832012-04-12 05:08:17 +00004748
JF Bastien7f0a05a2018-05-25 00:07:09 +00004749 // The first argument's non-CV pointer type is used to deduce the type of
4750 // subsequent arguments, except for:
4751 // - weak flag (always converted to bool)
4752 // - memory order (always converted to int)
4753 // - scope (always converted to int)
4754 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004755 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00004756 if (i < NumVals[Form] + 1) {
4757 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00004758 case 0:
4759 // The first argument is always a pointer. It has a fixed type.
4760 // It is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004761 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
JF Bastien7f0a05a2018-05-25 00:07:09 +00004762 // Nothing else to do: we already know all we want about this pointer.
4763 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00004764 case 1:
4765 // The second argument is the non-atomic operand. For arithmetic, this
4766 // is always passed by value, and for a compare_exchange it is always
4767 // passed by address. For the rest, GNU uses by-address and C11 uses
4768 // by-value.
4769 assert(Form != Load);
4770 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4771 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004772 else if (Form == Copy || Form == Xchg) {
4773 if (IsPassedByAddress)
4774 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004775 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004776 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004777 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00004778 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004779 else {
4780 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00004781 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004782 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
Alexander Richardson6d989432017-10-15 18:48:14 +00004783 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004784 // Keep address space of non-atomic pointer type.
4785 if (const PointerType *PtrTy =
4786 ValArg->getType()->getAs<PointerType>()) {
4787 AS = PtrTy->getPointeeType().getAddressSpace();
4788 }
4789 Ty = Context.getPointerType(
4790 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4791 }
Richard Smithfeea8832012-04-12 05:08:17 +00004792 break;
4793 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00004794 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00004795 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4796 if (IsPassedByAddress)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004797 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004798 Ty = ByValType;
4799 break;
4800 case 3:
4801 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4802 Ty = Context.BoolTy;
4803 break;
4804 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004805 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00004806 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004807 Ty = Context.IntTy;
4808 }
Richard Smithfeea8832012-04-12 05:08:17 +00004809
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004810 InitializedEntity Entity =
4811 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00004812 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004813 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4814 if (Arg.isInvalid())
4815 return true;
4816 TheCall->setArg(i, Arg.get());
4817 }
4818
Richard Smithfeea8832012-04-12 05:08:17 +00004819 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004820 SmallVector<Expr*, 5> SubExprs;
4821 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00004822 switch (Form) {
4823 case Init:
4824 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00004825 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004826 break;
4827 case Load:
4828 SubExprs.push_back(TheCall->getArg(1)); // Order
4829 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00004830 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00004831 case Copy:
4832 case Arithmetic:
4833 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004834 SubExprs.push_back(TheCall->getArg(2)); // Order
4835 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004836 break;
4837 case GNUXchg:
4838 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4839 SubExprs.push_back(TheCall->getArg(3)); // Order
4840 SubExprs.push_back(TheCall->getArg(1)); // Val1
4841 SubExprs.push_back(TheCall->getArg(2)); // Val2
4842 break;
4843 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004844 SubExprs.push_back(TheCall->getArg(3)); // Order
4845 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004846 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00004847 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00004848 break;
4849 case GNUCmpXchg:
4850 SubExprs.push_back(TheCall->getArg(4)); // Order
4851 SubExprs.push_back(TheCall->getArg(1)); // Val1
4852 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4853 SubExprs.push_back(TheCall->getArg(2)); // Val2
4854 SubExprs.push_back(TheCall->getArg(3)); // Weak
4855 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004856 }
Tim Northovere94a34c2014-03-11 10:49:14 +00004857
4858 if (SubExprs.size() >= 2 && Form != Init) {
4859 llvm::APSInt Result(32);
4860 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4861 !isValidOrderingForOp(Result.getSExtValue(), Op))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004862 Diag(SubExprs[1]->getBeginLoc(),
Tim Northoverc83472e2014-03-11 11:35:10 +00004863 diag::warn_atomic_op_has_invalid_memory_order)
4864 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00004865 }
4866
Yaxun Liu30d652a2017-08-15 16:02:49 +00004867 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4868 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4869 llvm::APSInt Result(32);
4870 if (Scope->isIntegerConstantExpr(Result, Context) &&
4871 !ScopeModel->isValid(Result.getZExtValue())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004872 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
Yaxun Liu30d652a2017-08-15 16:02:49 +00004873 << Scope->getSourceRange();
4874 }
4875 SubExprs.push_back(Scope);
4876 }
4877
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004878 AtomicExpr *AE =
4879 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4880 ResultType, Op, TheCall->getRParenLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00004881
Fariborz Jahanian615de762013-05-28 17:37:39 +00004882 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00004883 Op == AtomicExpr::AO__c11_atomic_store ||
4884 Op == AtomicExpr::AO__opencl_atomic_load ||
4885 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00004886 Context.AtomicUsesUnsupportedLibcall(AE))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004887 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
Yaxun Liu39195062017-08-04 18:16:31 +00004888 << ((Op == AtomicExpr::AO__c11_atomic_load ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004889 Op == AtomicExpr::AO__opencl_atomic_load)
4890 ? 0
4891 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004892
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004893 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004894}
4895
John McCall29ad95b2011-08-27 01:09:30 +00004896/// checkBuiltinArgument - Given a call to a builtin function, perform
4897/// normal type-checking on the given argument, updating the call in
4898/// place. This is useful when a builtin function requires custom
4899/// type-checking for some of its arguments but not necessarily all of
4900/// them.
4901///
4902/// Returns true on error.
4903static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4904 FunctionDecl *Fn = E->getDirectCallee();
4905 assert(Fn && "builtin call without direct callee!");
4906
4907 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4908 InitializedEntity Entity =
4909 InitializedEntity::InitializeParameter(S.Context, Param);
4910
4911 ExprResult Arg = E->getArg(0);
4912 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4913 if (Arg.isInvalid())
4914 return true;
4915
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004916 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00004917 return false;
4918}
4919
JF Bastiene77b48b2018-09-10 20:42:56 +00004920/// We have a call to a function like __sync_fetch_and_add, which is an
4921/// overloaded function based on the pointer type of its first argument.
Richard Smith255b85f2019-05-08 01:36:36 +00004922/// The main BuildCallExpr routines have already promoted the types of
JF Bastiene77b48b2018-09-10 20:42:56 +00004923/// arguments because all of these calls are prototyped as void(...).
Chris Lattnerdc046542009-05-08 06:58:22 +00004924///
4925/// This function goes through and does final semantic checking for these
JF Bastiene77b48b2018-09-10 20:42:56 +00004926/// builtins, as well as generating any warnings.
John McCalldadc5752010-08-24 06:29:42 +00004927ExprResult
4928Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
JF Bastiene77b48b2018-09-10 20:42:56 +00004929 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4930 Expr *Callee = TheCall->getCallee();
4931 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
Chris Lattnerdc046542009-05-08 06:58:22 +00004932 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4933
4934 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004935 if (TheCall->getNumArgs() < 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004936 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
JF Bastiene77b48b2018-09-10 20:42:56 +00004937 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004938 return ExprError();
4939 }
Mike Stump11289f42009-09-09 15:08:12 +00004940
Chris Lattnerdc046542009-05-08 06:58:22 +00004941 // Inspect the first argument of the atomic builtin. This should always be
4942 // a pointer type, whose element is an integral scalar or pointer type.
4943 // Because it is a pointer type, we don't have to worry about any implicit
4944 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004945 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00004946 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00004947 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4948 if (FirstArgResult.isInvalid())
4949 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004950 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00004951 TheCall->setArg(0, FirstArg);
4952
John McCall31168b02011-06-15 23:02:42 +00004953 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4954 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004955 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4956 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004957 return ExprError();
4958 }
Mike Stump11289f42009-09-09 15:08:12 +00004959
John McCall31168b02011-06-15 23:02:42 +00004960 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00004961 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004962 !ValType->isBlockPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004963 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4964 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004965 return ExprError();
4966 }
Chris Lattnerdc046542009-05-08 06:58:22 +00004967
Aaron Ballmana383c942018-05-05 17:38:42 +00004968 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004969 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
Aaron Ballmana383c942018-05-05 17:38:42 +00004970 << FirstArg->getType() << FirstArg->getSourceRange();
4971 return ExprError();
4972 }
4973
John McCall31168b02011-06-15 23:02:42 +00004974 switch (ValType.getObjCLifetime()) {
4975 case Qualifiers::OCL_None:
4976 case Qualifiers::OCL_ExplicitNone:
4977 // okay
4978 break;
4979
4980 case Qualifiers::OCL_Weak:
4981 case Qualifiers::OCL_Strong:
4982 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004983 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4984 << ValType << FirstArg->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004985 return ExprError();
4986 }
4987
John McCallb50451a2011-10-05 07:41:44 +00004988 // Strip any qualifiers off ValType.
4989 ValType = ValType.getUnqualifiedType();
4990
Chandler Carruth3973af72010-07-18 20:54:12 +00004991 // The majority of builtins return a value, but a few have special return
4992 // types, so allow them to override appropriately below.
4993 QualType ResultType = ValType;
4994
Chris Lattnerdc046542009-05-08 06:58:22 +00004995 // We need to figure out which concrete builtin this maps onto. For example,
4996 // __sync_fetch_and_add with a 2 byte object turns into
4997 // __sync_fetch_and_add_2.
4998#define BUILTIN_ROW(x) \
4999 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5000 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00005001
Chris Lattnerdc046542009-05-08 06:58:22 +00005002 static const unsigned BuiltinIndices[][5] = {
5003 BUILTIN_ROW(__sync_fetch_and_add),
5004 BUILTIN_ROW(__sync_fetch_and_sub),
5005 BUILTIN_ROW(__sync_fetch_and_or),
5006 BUILTIN_ROW(__sync_fetch_and_and),
5007 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00005008 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00005009
Chris Lattnerdc046542009-05-08 06:58:22 +00005010 BUILTIN_ROW(__sync_add_and_fetch),
5011 BUILTIN_ROW(__sync_sub_and_fetch),
5012 BUILTIN_ROW(__sync_and_and_fetch),
5013 BUILTIN_ROW(__sync_or_and_fetch),
5014 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00005015 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00005016
Chris Lattnerdc046542009-05-08 06:58:22 +00005017 BUILTIN_ROW(__sync_val_compare_and_swap),
5018 BUILTIN_ROW(__sync_bool_compare_and_swap),
5019 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00005020 BUILTIN_ROW(__sync_lock_release),
5021 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00005022 };
Mike Stump11289f42009-09-09 15:08:12 +00005023#undef BUILTIN_ROW
5024
Chris Lattnerdc046542009-05-08 06:58:22 +00005025 // Determine the index of the size.
5026 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00005027 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00005028 case 1: SizeIndex = 0; break;
5029 case 2: SizeIndex = 1; break;
5030 case 4: SizeIndex = 2; break;
5031 case 8: SizeIndex = 3; break;
5032 case 16: SizeIndex = 4; break;
5033 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005034 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5035 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005036 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00005037 }
Mike Stump11289f42009-09-09 15:08:12 +00005038
Chris Lattnerdc046542009-05-08 06:58:22 +00005039 // Each of these builtins has one pointer argument, followed by some number of
5040 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5041 // that we ignore. Find out which row of BuiltinIndices to read from as well
5042 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00005043 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00005044 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00005045 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00005046 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00005047 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Fangrui Song6907ce22018-07-30 19:24:48 +00005048 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00005049 case Builtin::BI__sync_fetch_and_add_1:
5050 case Builtin::BI__sync_fetch_and_add_2:
5051 case Builtin::BI__sync_fetch_and_add_4:
5052 case Builtin::BI__sync_fetch_and_add_8:
5053 case Builtin::BI__sync_fetch_and_add_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005054 BuiltinIndex = 0;
Douglas Gregor73722482011-11-28 16:30:08 +00005055 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005056
5057 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00005058 case Builtin::BI__sync_fetch_and_sub_1:
5059 case Builtin::BI__sync_fetch_and_sub_2:
5060 case Builtin::BI__sync_fetch_and_sub_4:
5061 case Builtin::BI__sync_fetch_and_sub_8:
5062 case Builtin::BI__sync_fetch_and_sub_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005063 BuiltinIndex = 1;
Douglas Gregor73722482011-11-28 16:30:08 +00005064 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005065
5066 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00005067 case Builtin::BI__sync_fetch_and_or_1:
5068 case Builtin::BI__sync_fetch_and_or_2:
5069 case Builtin::BI__sync_fetch_and_or_4:
5070 case Builtin::BI__sync_fetch_and_or_8:
5071 case Builtin::BI__sync_fetch_and_or_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005072 BuiltinIndex = 2;
Douglas Gregor73722482011-11-28 16:30:08 +00005073 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005074
5075 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00005076 case Builtin::BI__sync_fetch_and_and_1:
5077 case Builtin::BI__sync_fetch_and_and_2:
5078 case Builtin::BI__sync_fetch_and_and_4:
5079 case Builtin::BI__sync_fetch_and_and_8:
5080 case Builtin::BI__sync_fetch_and_and_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005081 BuiltinIndex = 3;
Douglas Gregor73722482011-11-28 16:30:08 +00005082 break;
Mike Stump11289f42009-09-09 15:08:12 +00005083
Fangrui Song6907ce22018-07-30 19:24:48 +00005084 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00005085 case Builtin::BI__sync_fetch_and_xor_1:
5086 case Builtin::BI__sync_fetch_and_xor_2:
5087 case Builtin::BI__sync_fetch_and_xor_4:
5088 case Builtin::BI__sync_fetch_and_xor_8:
5089 case Builtin::BI__sync_fetch_and_xor_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005090 BuiltinIndex = 4;
Douglas Gregor73722482011-11-28 16:30:08 +00005091 break;
5092
Fangrui Song6907ce22018-07-30 19:24:48 +00005093 case Builtin::BI__sync_fetch_and_nand:
Hal Finkeld2208b52014-10-02 20:53:50 +00005094 case Builtin::BI__sync_fetch_and_nand_1:
5095 case Builtin::BI__sync_fetch_and_nand_2:
5096 case Builtin::BI__sync_fetch_and_nand_4:
5097 case Builtin::BI__sync_fetch_and_nand_8:
5098 case Builtin::BI__sync_fetch_and_nand_16:
5099 BuiltinIndex = 5;
5100 WarnAboutSemanticsChange = true;
5101 break;
5102
Fangrui Song6907ce22018-07-30 19:24:48 +00005103 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005104 case Builtin::BI__sync_add_and_fetch_1:
5105 case Builtin::BI__sync_add_and_fetch_2:
5106 case Builtin::BI__sync_add_and_fetch_4:
5107 case Builtin::BI__sync_add_and_fetch_8:
5108 case Builtin::BI__sync_add_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005109 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00005110 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005111
5112 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005113 case Builtin::BI__sync_sub_and_fetch_1:
5114 case Builtin::BI__sync_sub_and_fetch_2:
5115 case Builtin::BI__sync_sub_and_fetch_4:
5116 case Builtin::BI__sync_sub_and_fetch_8:
5117 case Builtin::BI__sync_sub_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005118 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00005119 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005120
5121 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005122 case Builtin::BI__sync_and_and_fetch_1:
5123 case Builtin::BI__sync_and_and_fetch_2:
5124 case Builtin::BI__sync_and_and_fetch_4:
5125 case Builtin::BI__sync_and_and_fetch_8:
5126 case Builtin::BI__sync_and_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005127 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00005128 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005129
5130 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005131 case Builtin::BI__sync_or_and_fetch_1:
5132 case Builtin::BI__sync_or_and_fetch_2:
5133 case Builtin::BI__sync_or_and_fetch_4:
5134 case Builtin::BI__sync_or_and_fetch_8:
5135 case Builtin::BI__sync_or_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005136 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00005137 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005138
5139 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005140 case Builtin::BI__sync_xor_and_fetch_1:
5141 case Builtin::BI__sync_xor_and_fetch_2:
5142 case Builtin::BI__sync_xor_and_fetch_4:
5143 case Builtin::BI__sync_xor_and_fetch_8:
5144 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005145 BuiltinIndex = 10;
5146 break;
5147
Fangrui Song6907ce22018-07-30 19:24:48 +00005148 case Builtin::BI__sync_nand_and_fetch:
Hal Finkeld2208b52014-10-02 20:53:50 +00005149 case Builtin::BI__sync_nand_and_fetch_1:
5150 case Builtin::BI__sync_nand_and_fetch_2:
5151 case Builtin::BI__sync_nand_and_fetch_4:
5152 case Builtin::BI__sync_nand_and_fetch_8:
5153 case Builtin::BI__sync_nand_and_fetch_16:
5154 BuiltinIndex = 11;
5155 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00005156 break;
Mike Stump11289f42009-09-09 15:08:12 +00005157
Chris Lattnerdc046542009-05-08 06:58:22 +00005158 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005159 case Builtin::BI__sync_val_compare_and_swap_1:
5160 case Builtin::BI__sync_val_compare_and_swap_2:
5161 case Builtin::BI__sync_val_compare_and_swap_4:
5162 case Builtin::BI__sync_val_compare_and_swap_8:
5163 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005164 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00005165 NumFixed = 2;
5166 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005167
Chris Lattnerdc046542009-05-08 06:58:22 +00005168 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005169 case Builtin::BI__sync_bool_compare_and_swap_1:
5170 case Builtin::BI__sync_bool_compare_and_swap_2:
5171 case Builtin::BI__sync_bool_compare_and_swap_4:
5172 case Builtin::BI__sync_bool_compare_and_swap_8:
5173 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005174 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00005175 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00005176 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005177 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005178
JF Bastien7f0a05a2018-05-25 00:07:09 +00005179 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00005180 case Builtin::BI__sync_lock_test_and_set_1:
5181 case Builtin::BI__sync_lock_test_and_set_2:
5182 case Builtin::BI__sync_lock_test_and_set_4:
5183 case Builtin::BI__sync_lock_test_and_set_8:
5184 case Builtin::BI__sync_lock_test_and_set_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005185 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00005186 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005187
Chris Lattnerdc046542009-05-08 06:58:22 +00005188 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00005189 case Builtin::BI__sync_lock_release_1:
5190 case Builtin::BI__sync_lock_release_2:
5191 case Builtin::BI__sync_lock_release_4:
5192 case Builtin::BI__sync_lock_release_8:
5193 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005194 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00005195 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00005196 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005197 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005198
5199 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005200 case Builtin::BI__sync_swap_1:
5201 case Builtin::BI__sync_swap_2:
5202 case Builtin::BI__sync_swap_4:
5203 case Builtin::BI__sync_swap_8:
5204 case Builtin::BI__sync_swap_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005205 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00005206 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00005207 }
Mike Stump11289f42009-09-09 15:08:12 +00005208
Chris Lattnerdc046542009-05-08 06:58:22 +00005209 // Now that we know how many fixed arguments we expect, first check that we
5210 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005211 if (TheCall->getNumArgs() < 1+NumFixed) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005212 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5213 << 0 << 1 + NumFixed << TheCall->getNumArgs()
JF Bastiene77b48b2018-09-10 20:42:56 +00005214 << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005215 return ExprError();
5216 }
Mike Stump11289f42009-09-09 15:08:12 +00005217
JF Bastiene77b48b2018-09-10 20:42:56 +00005218 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5219 << Callee->getSourceRange();
5220
Hal Finkeld2208b52014-10-02 20:53:50 +00005221 if (WarnAboutSemanticsChange) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005222 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
JF Bastiene77b48b2018-09-10 20:42:56 +00005223 << Callee->getSourceRange();
Hal Finkeld2208b52014-10-02 20:53:50 +00005224 }
5225
Chris Lattner5b9241b2009-05-08 15:36:58 +00005226 // Get the decl for the concrete builtin from this, we can tell what the
5227 // concrete integer type we should convert to is.
5228 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00005229 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005230 FunctionDecl *NewBuiltinDecl;
5231 if (NewBuiltinID == BuiltinID)
5232 NewBuiltinDecl = FDecl;
5233 else {
5234 // Perform builtin lookup to avoid redeclaring it.
5235 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005236 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005237 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5238 assert(Res.getFoundDecl());
5239 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005240 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005241 return ExprError();
5242 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005243
John McCallcf142162010-08-07 06:22:56 +00005244 // The first argument --- the pointer --- has a fixed type; we
5245 // deduce the types of the rest of the arguments accordingly. Walk
5246 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00005247 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00005248 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00005249
Chris Lattnerdc046542009-05-08 06:58:22 +00005250 // GCC does an implicit conversion to the pointer or integer ValType. This
5251 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00005252 // Initialize the argument.
5253 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5254 ValType, /*consume*/ false);
5255 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00005256 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005257 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005258
Chris Lattnerdc046542009-05-08 06:58:22 +00005259 // Okay, we have something that *can* be converted to the right type. Check
5260 // to see if there is a potentially weird extension going on here. This can
5261 // happen when you do an atomic operation on something like an char* and
5262 // pass in 42. The 42 gets converted to char. This is even more strange
5263 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00005264 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005265 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00005266 }
Mike Stump11289f42009-09-09 15:08:12 +00005267
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005268 // Create a new DeclRefExpr to refer to the new decl.
Richard Smith715f7a12019-06-11 17:50:32 +00005269 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5270 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5271 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5272 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
Mike Stump11289f42009-09-09 15:08:12 +00005273
Chris Lattnerdc046542009-05-08 06:58:22 +00005274 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00005275 // FIXME: This loses syntactic information.
5276 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5277 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5278 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005279 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00005280
Chandler Carruthbc8cab12010-07-18 07:23:17 +00005281 // Change the result type of the call to match the original value type. This
5282 // is arbitrary, but the codegen for these builtins ins design to handle it
5283 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00005284 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005285
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005286 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00005287}
5288
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005289/// SemaBuiltinNontemporalOverloaded - We have a call to
5290/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5291/// overloaded function based on the pointer type of its last argument.
5292///
5293/// This function goes through and does final semantic checking for these
5294/// builtins.
5295ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5296 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5297 DeclRefExpr *DRE =
5298 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5299 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5300 unsigned BuiltinID = FDecl->getBuiltinID();
5301 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5302 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5303 "Unexpected nontemporal load/store builtin!");
5304 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5305 unsigned numArgs = isStore ? 2 : 1;
5306
5307 // Ensure that we have the proper number of arguments.
5308 if (checkArgCount(*this, TheCall, numArgs))
5309 return ExprError();
5310
5311 // Inspect the last argument of the nontemporal builtin. This should always
5312 // be a pointer type, from which we imply the type of the memory access.
5313 // Because it is a pointer type, we don't have to worry about any implicit
5314 // casts here.
5315 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5316 ExprResult PointerArgResult =
5317 DefaultFunctionArrayLvalueConversion(PointerArg);
5318
5319 if (PointerArgResult.isInvalid())
5320 return ExprError();
5321 PointerArg = PointerArgResult.get();
5322 TheCall->setArg(numArgs - 1, PointerArg);
5323
5324 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5325 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005326 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005327 << PointerArg->getType() << PointerArg->getSourceRange();
5328 return ExprError();
5329 }
5330
5331 QualType ValType = pointerType->getPointeeType();
5332
5333 // Strip any qualifiers off ValType.
5334 ValType = ValType.getUnqualifiedType();
5335 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5336 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5337 !ValType->isVectorType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005338 Diag(DRE->getBeginLoc(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005339 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5340 << PointerArg->getType() << PointerArg->getSourceRange();
5341 return ExprError();
5342 }
5343
5344 if (!isStore) {
5345 TheCall->setType(ValType);
5346 return TheCallResult;
5347 }
5348
5349 ExprResult ValArg = TheCall->getArg(0);
5350 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5351 Context, ValType, /*consume*/ false);
5352 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5353 if (ValArg.isInvalid())
5354 return ExprError();
5355
5356 TheCall->setArg(0, ValArg.get());
5357 TheCall->setType(Context.VoidTy);
5358 return TheCallResult;
5359}
5360
Chris Lattner6436fb62009-02-18 06:01:06 +00005361/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00005362/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00005363/// Note: It might also make sense to do the UTF-16 conversion here (would
5364/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00005365bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00005366 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00005367 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5368
Douglas Gregorfb65e592011-07-27 05:40:30 +00005369 if (!Literal || !Literal->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005370 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5371 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00005372 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00005373 }
Mike Stump11289f42009-09-09 15:08:12 +00005374
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005375 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005376 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005377 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00005378 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5379 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5380 llvm::UTF16 *ToPtr = &ToBuf[0];
5381
5382 llvm::ConversionResult Result =
5383 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5384 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005385 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00005386 if (Result != llvm::conversionOK)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005387 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5388 << Arg->getSourceRange();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005389 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00005390 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005391}
5392
Mehdi Amini06d367c2016-10-24 20:39:34 +00005393/// CheckObjCString - Checks that the format string argument to the os_log()
5394/// and os_trace() functions is correct, and converts it to const char *.
5395ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5396 Arg = Arg->IgnoreParenCasts();
5397 auto *Literal = dyn_cast<StringLiteral>(Arg);
5398 if (!Literal) {
5399 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5400 Literal = ObjcLiteral->getString();
5401 }
5402 }
5403
5404 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5405 return ExprError(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005406 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005407 << Arg->getSourceRange());
5408 }
5409
5410 ExprResult Result(Literal);
5411 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5412 InitializedEntity Entity =
5413 InitializedEntity::InitializeParameter(Context, ResultTy, false);
5414 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5415 return Result;
5416}
5417
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005418/// Check that the user is calling the appropriate va_start builtin for the
5419/// target and calling convention.
5420static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5421 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5422 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00005423 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005424 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00005425 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5426 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005427 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005428 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5429 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5430 if (IsMSVAStart) {
5431 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00005432 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005433 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005434 diag::err_ms_va_start_used_in_sysv_function);
5435 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00005436 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005437 // On x64 Windows, don't allow this in System V ABI functions.
5438 // (Yes, that means there's no corresponding way to support variadic
5439 // System V ABI functions on Windows.)
5440 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00005441 (!IsWindows && CC == CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005442 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005443 diag::err_va_start_used_in_wrong_abi_function)
5444 << !IsWindows;
5445 }
5446 return false;
5447 }
5448
5449 if (IsMSVAStart)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005450 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005451 return false;
5452}
5453
5454static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5455 ParmVarDecl **LastParam = nullptr) {
5456 // Determine whether the current function, block, or obj-c method is variadic
5457 // and get its parameter list.
5458 bool IsVariadic = false;
5459 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00005460 DeclContext *Caller = S.CurContext;
5461 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5462 IsVariadic = Block->isVariadic();
5463 Params = Block->parameters();
5464 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005465 IsVariadic = FD->isVariadic();
5466 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005467 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005468 IsVariadic = MD->isVariadic();
5469 // FIXME: This isn't correct for methods (results in bogus warning).
5470 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005471 } else if (isa<CapturedDecl>(Caller)) {
5472 // We don't support va_start in a CapturedDecl.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005473 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005474 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005475 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00005476 // This must be some other declcontext that parses exprs.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005477 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005478 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005479 }
5480
5481 if (!IsVariadic) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005482 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005483 return true;
5484 }
5485
5486 if (LastParam)
5487 *LastParam = Params.empty() ? nullptr : Params.back();
5488
5489 return false;
5490}
5491
Aaron Ballman68d50642018-06-19 14:53:20 +00005492/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5493/// for validity. Emit an error and return true on failure; return false
5494/// on success.
5495bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5496 Expr *Fn = TheCall->getCallee();
5497
5498 if (checkVAStartABI(*this, BuiltinID, Fn))
5499 return true;
5500
5501 if (TheCall->getNumArgs() > 2) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005502 Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005503 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005504 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5505 << Fn->getSourceRange()
5506 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005507 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005508 return true;
5509 }
5510
5511 if (TheCall->getNumArgs() < 2) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005512 return Diag(TheCall->getEndLoc(),
5513 diag::err_typecheck_call_too_few_args_at_least)
5514 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Aaron Ballman68d50642018-06-19 14:53:20 +00005515 }
5516
5517 // Type-check the first argument normally.
5518 if (checkBuiltinArgument(*this, TheCall, 0))
5519 return true;
5520
5521 // Check that the current function is variadic, and get its last parameter.
5522 ParmVarDecl *LastParam;
5523 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5524 return true;
5525
5526 // Verify that the second argument to the builtin is the last argument of the
5527 // current function or method.
5528 bool SecondArgIsLastNamedArgument = false;
5529 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5530
5531 // These are valid if SecondArgIsLastNamedArgument is false after the next
5532 // block.
5533 QualType Type;
5534 SourceLocation ParamLoc;
5535 bool IsCRegister = false;
5536
5537 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5538 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5539 SecondArgIsLastNamedArgument = PV == LastParam;
5540
5541 Type = PV->getType();
5542 ParamLoc = PV->getLocation();
5543 IsCRegister =
5544 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5545 }
5546 }
5547
5548 if (!SecondArgIsLastNamedArgument)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005549 Diag(TheCall->getArg(1)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005550 diag::warn_second_arg_of_va_start_not_last_named_param);
5551 else if (IsCRegister || Type->isReferenceType() ||
5552 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5553 // Promotable integers are UB, but enumerations need a bit of
5554 // extra checking to see what their promotable type actually is.
5555 if (!Type->isPromotableIntegerType())
5556 return false;
5557 if (!Type->isEnumeralType())
5558 return true;
5559 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5560 return !(ED &&
5561 Context.typesAreCompatible(ED->getPromotionType(), Type));
5562 }()) {
5563 unsigned Reason = 0;
5564 if (Type->isReferenceType()) Reason = 1;
5565 else if (IsCRegister) Reason = 2;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005566 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
Aaron Ballman68d50642018-06-19 14:53:20 +00005567 Diag(ParamLoc, diag::note_parameter_type) << Type;
5568 }
5569
5570 TheCall->setType(Context.VoidTy);
5571 return false;
5572}
5573
5574bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5575 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5576 // const char *named_addr);
5577
5578 Expr *Func = Call->getCallee();
5579
5580 if (Call->getNumArgs() < 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005581 return Diag(Call->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005582 diag::err_typecheck_call_too_few_args_at_least)
5583 << 0 /*function call*/ << 3 << Call->getNumArgs();
5584
5585 // Type-check the first argument normally.
5586 if (checkBuiltinArgument(*this, Call, 0))
5587 return true;
5588
5589 // Check that the current function is variadic.
5590 if (checkVAStartIsInVariadicFunction(*this, Func))
5591 return true;
5592
5593 // __va_start on Windows does not validate the parameter qualifiers
5594
5595 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5596 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5597
5598 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5599 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5600
5601 const QualType &ConstCharPtrTy =
5602 Context.getPointerType(Context.CharTy.withConst());
5603 if (!Arg1Ty->isPointerType() ||
5604 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005605 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5606 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5607 << 0 /* qualifier difference */
5608 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005609 << 2 << Arg1->getType() << ConstCharPtrTy;
5610
5611 const QualType SizeTy = Context.getSizeType();
5612 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005613 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5614 << Arg2->getType() << SizeTy << 1 /* different class */
5615 << 0 /* qualifier difference */
5616 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005617 << 3 << Arg2->getType() << SizeTy;
5618
5619 return false;
5620}
5621
5622/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5623/// friends. This is declared to take (...), so we have to check everything.
5624bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5625 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005626 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5627 << 0 << 2 << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005628 if (TheCall->getNumArgs() > 2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005629 return Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005630 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005631 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5632 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005633 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005634
5635 ExprResult OrigArg0 = TheCall->getArg(0);
5636 ExprResult OrigArg1 = TheCall->getArg(1);
5637
5638 // Do standard promotions between the two arguments, returning their common
5639 // type.
5640 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5641 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5642 return true;
5643
5644 // Make sure any conversions are pushed back into the call; this is
5645 // type safe since unordered compare builtins are declared as "_Bool
5646 // foo(...)".
5647 TheCall->setArg(0, OrigArg0.get());
5648 TheCall->setArg(1, OrigArg1.get());
5649
5650 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5651 return false;
5652
5653 // If the common type isn't a real floating type, then the arguments were
5654 // invalid for this operation.
5655 if (Res.isNull() || !Res->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005656 return Diag(OrigArg0.get()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005657 diag::err_typecheck_call_invalid_ordered_compare)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005658 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5659 << SourceRange(OrigArg0.get()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005660 OrigArg1.get()->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005661
5662 return false;
5663}
5664
5665/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5666/// __builtin_isnan and friends. This is declared to take (...), so we have
5667/// to check everything. We expect the last argument to be a floating point
5668/// value.
5669bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5670 if (TheCall->getNumArgs() < NumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005671 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5672 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005673 if (TheCall->getNumArgs() > NumArgs)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005674 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005675 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005676 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5677 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005678 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005679
5680 Expr *OrigArg = TheCall->getArg(NumArgs-1);
5681
5682 if (OrigArg->isTypeDependent())
5683 return false;
5684
5685 // This operation requires a non-_Complex floating-point number.
5686 if (!OrigArg->getType()->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005687 return Diag(OrigArg->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005688 diag::err_typecheck_call_invalid_unary_fp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005689 << OrigArg->getType() << OrigArg->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005690
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005691 // If this is an implicit conversion from float -> float, double, or
5692 // long double, remove it.
Aaron Ballman68d50642018-06-19 14:53:20 +00005693 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5694 // Only remove standard FloatCasts, leaving other casts inplace
5695 if (Cast->getCastKind() == CK_FloatingCast) {
5696 Expr *CastArg = Cast->getSubExpr();
5697 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005698 assert(
5699 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5700 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5701 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5702 "promotion from float to either float, double, or long double is "
5703 "the only expected cast here");
Aaron Ballman68d50642018-06-19 14:53:20 +00005704 Cast->setSubExpr(nullptr);
5705 TheCall->setArg(NumArgs-1, CastArg);
5706 }
5707 }
5708 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005709
Aaron Ballman68d50642018-06-19 14:53:20 +00005710 return false;
5711}
5712
5713// Customized Sema Checking for VSX builtins that have the following signature:
5714// vector [...] builtinName(vector [...], vector [...], const int);
5715// Which takes the same type of vectors (any legal vector type) for the first
5716// two arguments and takes compile time constant for the third argument.
5717// Example builtins are :
5718// vector double vec_xxpermdi(vector double, vector double, int);
5719// vector short vec_xxsldwi(vector short, vector short, int);
5720bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5721 unsigned ExpectedNumArgs = 3;
5722 if (TheCall->getNumArgs() < ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005723 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005724 diag::err_typecheck_call_too_few_args_at_least)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005725 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
Aaron Ballman68d50642018-06-19 14:53:20 +00005726 << TheCall->getSourceRange();
5727
5728 if (TheCall->getNumArgs() > ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005729 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005730 diag::err_typecheck_call_too_many_args_at_most)
5731 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5732 << TheCall->getSourceRange();
5733
5734 // Check the third argument is a compile time constant
5735 llvm::APSInt Value;
5736 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005737 return Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005738 diag::err_vsx_builtin_nonconstant_argument)
5739 << 3 /* argument index */ << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005740 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005741 TheCall->getArg(2)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005742
5743 QualType Arg1Ty = TheCall->getArg(0)->getType();
5744 QualType Arg2Ty = TheCall->getArg(1)->getType();
5745
5746 // Check the type of argument 1 and argument 2 are vectors.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005747 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
Aaron Ballman68d50642018-06-19 14:53:20 +00005748 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5749 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5750 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5751 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005752 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005753 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005754 }
5755
5756 // Check the first two arguments are the same type.
5757 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5758 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5759 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005760 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005761 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005762 }
5763
5764 // When default clang type checking is turned off and the customized type
5765 // checking is used, the returning type of the function must be explicitly
5766 // set. Otherwise it is _Bool by default.
5767 TheCall->setType(Arg1Ty);
5768
5769 return false;
5770}
5771
5772/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5773// This is declared to take (...), so we have to check everything.
5774ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5775 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005776 return ExprError(Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005777 diag::err_typecheck_call_too_few_args_at_least)
5778 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5779 << TheCall->getSourceRange());
5780
5781 // Determine which of the following types of shufflevector we're checking:
5782 // 1) unary, vector mask: (lhs, mask)
5783 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5784 QualType resType = TheCall->getArg(0)->getType();
5785 unsigned numElements = 0;
5786
5787 if (!TheCall->getArg(0)->isTypeDependent() &&
5788 !TheCall->getArg(1)->isTypeDependent()) {
5789 QualType LHSType = TheCall->getArg(0)->getType();
5790 QualType RHSType = TheCall->getArg(1)->getType();
5791
5792 if (!LHSType->isVectorType() || !RHSType->isVectorType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005793 return ExprError(
5794 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5795 << TheCall->getDirectCallee()
5796 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005797 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005798
5799 numElements = LHSType->getAs<VectorType>()->getNumElements();
5800 unsigned numResElements = TheCall->getNumArgs() - 2;
5801
5802 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5803 // with mask. If so, verify that RHS is an integer vector type with the
5804 // same number of elts as lhs.
5805 if (TheCall->getNumArgs() == 2) {
5806 if (!RHSType->hasIntegerRepresentation() ||
5807 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005808 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005809 diag::err_vec_builtin_incompatible_vector)
5810 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005811 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005812 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005813 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005814 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005815 diag::err_vec_builtin_incompatible_vector)
5816 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005817 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005818 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005819 } else if (numElements != numResElements) {
5820 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5821 resType = Context.getVectorType(eltType, numResElements,
5822 VectorType::GenericVector);
5823 }
5824 }
5825
5826 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5827 if (TheCall->getArg(i)->isTypeDependent() ||
5828 TheCall->getArg(i)->isValueDependent())
5829 continue;
5830
5831 llvm::APSInt Result(32);
5832 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005833 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005834 diag::err_shufflevector_nonconstant_argument)
5835 << TheCall->getArg(i)->getSourceRange());
5836
5837 // Allow -1 which will be translated to undef in the IR.
5838 if (Result.isSigned() && Result.isAllOnesValue())
5839 continue;
5840
5841 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005842 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005843 diag::err_shufflevector_argument_too_large)
5844 << TheCall->getArg(i)->getSourceRange());
5845 }
5846
5847 SmallVector<Expr*, 32> exprs;
5848
5849 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5850 exprs.push_back(TheCall->getArg(i));
5851 TheCall->setArg(i, nullptr);
5852 }
5853
5854 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005855 TheCall->getCallee()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005856 TheCall->getRParenLoc());
5857}
5858
5859/// SemaConvertVectorExpr - Handle __builtin_convertvector
5860ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5861 SourceLocation BuiltinLoc,
5862 SourceLocation RParenLoc) {
5863 ExprValueKind VK = VK_RValue;
5864 ExprObjectKind OK = OK_Ordinary;
5865 QualType DstTy = TInfo->getType();
5866 QualType SrcTy = E->getType();
5867
5868 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5869 return ExprError(Diag(BuiltinLoc,
5870 diag::err_convertvector_non_vector)
5871 << E->getSourceRange());
5872 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5873 return ExprError(Diag(BuiltinLoc,
5874 diag::err_convertvector_non_vector_type));
5875
5876 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5877 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5878 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5879 if (SrcElts != DstElts)
5880 return ExprError(Diag(BuiltinLoc,
5881 diag::err_convertvector_incompatible_vector)
5882 << E->getSourceRange());
5883 }
5884
5885 return new (Context)
5886 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5887}
5888
5889/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5890// This is declared to take (const void*, ...) and can take two
5891// optional constant int args.
5892bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5893 unsigned NumArgs = TheCall->getNumArgs();
5894
5895 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005896 return Diag(TheCall->getEndLoc(),
5897 diag::err_typecheck_call_too_many_args_at_most)
5898 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005899
5900 // Argument 0 is checked for us and the remaining arguments must be
5901 // constant integers.
5902 for (unsigned i = 1; i != NumArgs; ++i)
Richard Sandiford28940af2014-04-16 08:47:51 +00005903 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005904 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005905
Warren Hunt20e4a5d2014-02-21 23:08:53 +00005906 return false;
5907}
5908
Hal Finkelf0417332014-07-17 14:25:55 +00005909/// SemaBuiltinAssume - Handle __assume (MS Extension).
5910// __assume does not evaluate its arguments, and should warn if its argument
5911// has side effects.
5912bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5913 Expr *Arg = TheCall->getArg(0);
5914 if (Arg->isInstantiationDependent()) return false;
5915
5916 if (Arg->HasSideEffects(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005917 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5918 << Arg->getSourceRange()
5919 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
Hal Finkelbcc06082014-09-07 22:58:14 +00005920
5921 return false;
5922}
5923
David Majnemer86b1bfa2016-10-31 18:07:57 +00005924/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00005925/// as (size_t, size_t) where the second size_t must be a power of 2 greater
5926/// than 8.
5927bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5928 // The alignment must be a constant integer.
5929 Expr *Arg = TheCall->getArg(1);
5930
5931 // We can't check the value of a dependent argument.
5932 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00005933 if (const auto *UE =
5934 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
Richard Smith6822bd72018-10-26 19:26:45 +00005935 if (UE->getKind() == UETT_AlignOf ||
5936 UE->getKind() == UETT_PreferredAlignOf)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005937 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5938 << Arg->getSourceRange();
David Majnemer86b1bfa2016-10-31 18:07:57 +00005939
David Majnemer51169932016-10-31 05:37:48 +00005940 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5941
5942 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005943 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5944 << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005945
5946 if (Result < Context.getCharWidth())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005947 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5948 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005949
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005950 if (Result > std::numeric_limits<int32_t>::max())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005951 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5952 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005953 }
5954
5955 return false;
5956}
5957
5958/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00005959/// as (const void*, size_t, ...) and can take one optional constant int arg.
5960bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5961 unsigned NumArgs = TheCall->getNumArgs();
5962
5963 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005964 return Diag(TheCall->getEndLoc(),
5965 diag::err_typecheck_call_too_many_args_at_most)
5966 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005967
5968 // The alignment must be a constant integer.
5969 Expr *Arg = TheCall->getArg(1);
5970
5971 // We can't check the value of a dependent argument.
5972 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5973 llvm::APSInt Result;
5974 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5975 return true;
5976
5977 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005978 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5979 << Arg->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005980 }
5981
5982 if (NumArgs > 2) {
5983 ExprResult Arg(TheCall->getArg(2));
5984 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5985 Context.getSizeType(), false);
5986 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5987 if (Arg.isInvalid()) return true;
5988 TheCall->setArg(2, Arg.get());
5989 }
Hal Finkelf0417332014-07-17 14:25:55 +00005990
5991 return false;
5992}
5993
Mehdi Amini06d367c2016-10-24 20:39:34 +00005994bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5995 unsigned BuiltinID =
5996 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5997 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5998
5999 unsigned NumArgs = TheCall->getNumArgs();
6000 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6001 if (NumArgs < NumRequiredArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006002 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006003 << 0 /* function call */ << NumRequiredArgs << NumArgs
6004 << TheCall->getSourceRange();
6005 }
6006 if (NumArgs >= NumRequiredArgs + 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006007 return Diag(TheCall->getEndLoc(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00006008 diag::err_typecheck_call_too_many_args_at_most)
6009 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6010 << TheCall->getSourceRange();
6011 }
6012 unsigned i = 0;
6013
6014 // For formatting call, check buffer arg.
6015 if (!IsSizeCall) {
6016 ExprResult Arg(TheCall->getArg(i));
6017 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6018 Context, Context.VoidPtrTy, false);
6019 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6020 if (Arg.isInvalid())
6021 return true;
6022 TheCall->setArg(i, Arg.get());
6023 i++;
6024 }
6025
6026 // Check string literal arg.
6027 unsigned FormatIdx = i;
6028 {
6029 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6030 if (Arg.isInvalid())
6031 return true;
6032 TheCall->setArg(i, Arg.get());
6033 i++;
6034 }
6035
6036 // Make sure variadic args are scalar.
6037 unsigned FirstDataArg = i;
6038 while (i < NumArgs) {
6039 ExprResult Arg = DefaultVariadicArgumentPromotion(
6040 TheCall->getArg(i), VariadicFunction, nullptr);
6041 if (Arg.isInvalid())
6042 return true;
6043 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6044 if (ArgSize.getQuantity() >= 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006045 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006046 << i << (int)ArgSize.getQuantity() << 0xff
6047 << TheCall->getSourceRange();
6048 }
6049 TheCall->setArg(i, Arg.get());
6050 i++;
6051 }
6052
6053 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6054 // call to avoid duplicate diagnostics.
6055 if (!IsSizeCall) {
6056 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6057 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6058 bool Success = CheckFormatArguments(
6059 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006060 VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00006061 CheckedVarArgs);
6062 if (!Success)
6063 return true;
6064 }
6065
6066 if (IsSizeCall) {
6067 TheCall->setType(Context.getSizeType());
6068 } else {
6069 TheCall->setType(Context.VoidPtrTy);
6070 }
6071 return false;
6072}
6073
Eric Christopher8d0c6212010-04-17 02:26:23 +00006074/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6075/// TheCall is a constant expression.
6076bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6077 llvm::APSInt &Result) {
6078 Expr *Arg = TheCall->getArg(ArgNum);
6079 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6080 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00006081
Eric Christopher8d0c6212010-04-17 02:26:23 +00006082 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006083
Eric Christopher8d0c6212010-04-17 02:26:23 +00006084 if (!Arg->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006085 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6086 << FDecl->getDeclName() << Arg->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00006087
Chris Lattnerd545ad12009-09-23 06:06:36 +00006088 return false;
6089}
6090
Richard Sandiford28940af2014-04-16 08:47:51 +00006091/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6092/// TheCall is a constant expression in the range [Low, High].
6093bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006094 int Low, int High, bool RangeIsError) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00006095 if (isConstantEvaluated())
6096 return false;
Eric Christopher8d0c6212010-04-17 02:26:23 +00006097 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00006098
6099 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00006100 Expr *Arg = TheCall->getArg(ArgNum);
6101 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00006102 return false;
6103
Eric Christopher8d0c6212010-04-17 02:26:23 +00006104 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00006105 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00006106 return true;
6107
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006108 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6109 if (RangeIsError)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006110 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006111 << Result.toString(10) << Low << High << Arg->getSourceRange();
6112 else
6113 // Defer the warning until we know if the code will be emitted so that
6114 // dead code can ignore this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006115 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6116 PDiag(diag::warn_argument_invalid_range)
6117 << Result.toString(10) << Low << High
6118 << Arg->getSourceRange());
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006119 }
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00006120
6121 return false;
6122}
6123
Simon Dardis1f90f2d2016-10-19 17:50:52 +00006124/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6125/// TheCall is a constant expression is a multiple of Num..
6126bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6127 unsigned Num) {
6128 llvm::APSInt Result;
6129
6130 // We can't check the value of a dependent argument.
6131 Expr *Arg = TheCall->getArg(ArgNum);
6132 if (Arg->isTypeDependent() || Arg->isValueDependent())
6133 return false;
6134
6135 // Check constant-ness first.
6136 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6137 return true;
6138
6139 if (Result.getSExtValue() % Num != 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006140 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6141 << Num << Arg->getSourceRange();
Simon Dardis1f90f2d2016-10-19 17:50:52 +00006142
6143 return false;
6144}
6145
Javed Absar18b0c402019-04-26 21:08:11 +00006146/// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6147bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6148 if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6149 if (checkArgCount(*this, TheCall, 2))
6150 return true;
6151 Expr *Arg0 = TheCall->getArg(0);
6152 Expr *Arg1 = TheCall->getArg(1);
6153
6154 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6155 if (FirstArg.isInvalid())
6156 return true;
6157 QualType FirstArgType = FirstArg.get()->getType();
6158 if (!FirstArgType->isAnyPointerType())
6159 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6160 << "first" << FirstArgType << Arg0->getSourceRange();
6161 TheCall->setArg(0, FirstArg.get());
6162
6163 ExprResult SecArg = DefaultLvalueConversion(Arg1);
6164 if (SecArg.isInvalid())
6165 return true;
6166 QualType SecArgType = SecArg.get()->getType();
6167 if (!SecArgType->isIntegerType())
6168 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6169 << "second" << SecArgType << Arg1->getSourceRange();
6170
6171 // Derive the return type from the pointer argument.
6172 TheCall->setType(FirstArgType);
6173 return false;
6174 }
6175
6176 if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6177 if (checkArgCount(*this, TheCall, 2))
6178 return true;
6179
6180 Expr *Arg0 = TheCall->getArg(0);
6181 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6182 if (FirstArg.isInvalid())
6183 return true;
6184 QualType FirstArgType = FirstArg.get()->getType();
6185 if (!FirstArgType->isAnyPointerType())
6186 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6187 << "first" << FirstArgType << Arg0->getSourceRange();
6188 TheCall->setArg(0, FirstArg.get());
6189
6190 // Derive the return type from the pointer argument.
6191 TheCall->setType(FirstArgType);
6192
6193 // Second arg must be an constant in range [0,15]
6194 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6195 }
6196
6197 if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6198 if (checkArgCount(*this, TheCall, 2))
6199 return true;
6200 Expr *Arg0 = TheCall->getArg(0);
6201 Expr *Arg1 = TheCall->getArg(1);
6202
6203 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6204 if (FirstArg.isInvalid())
6205 return true;
6206 QualType FirstArgType = FirstArg.get()->getType();
6207 if (!FirstArgType->isAnyPointerType())
6208 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6209 << "first" << FirstArgType << Arg0->getSourceRange();
6210
6211 QualType SecArgType = Arg1->getType();
6212 if (!SecArgType->isIntegerType())
6213 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6214 << "second" << SecArgType << Arg1->getSourceRange();
6215 TheCall->setType(Context.IntTy);
6216 return false;
6217 }
6218
6219 if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6220 BuiltinID == AArch64::BI__builtin_arm_stg) {
6221 if (checkArgCount(*this, TheCall, 1))
6222 return true;
6223 Expr *Arg0 = TheCall->getArg(0);
6224 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6225 if (FirstArg.isInvalid())
6226 return true;
6227
6228 QualType FirstArgType = FirstArg.get()->getType();
6229 if (!FirstArgType->isAnyPointerType())
6230 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6231 << "first" << FirstArgType << Arg0->getSourceRange();
6232 TheCall->setArg(0, FirstArg.get());
6233
6234 // Derive the return type from the pointer argument.
6235 if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6236 TheCall->setType(FirstArgType);
6237 return false;
6238 }
6239
6240 if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6241 Expr *ArgA = TheCall->getArg(0);
6242 Expr *ArgB = TheCall->getArg(1);
6243
6244 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6245 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6246
6247 if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6248 return true;
6249
6250 QualType ArgTypeA = ArgExprA.get()->getType();
6251 QualType ArgTypeB = ArgExprB.get()->getType();
6252
6253 auto isNull = [&] (Expr *E) -> bool {
6254 return E->isNullPointerConstant(
6255 Context, Expr::NPC_ValueDependentIsNotNull); };
6256
6257 // argument should be either a pointer or null
6258 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6259 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6260 << "first" << ArgTypeA << ArgA->getSourceRange();
6261
6262 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6263 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6264 << "second" << ArgTypeB << ArgB->getSourceRange();
6265
6266 // Ensure Pointee types are compatible
6267 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6268 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6269 QualType pointeeA = ArgTypeA->getPointeeType();
6270 QualType pointeeB = ArgTypeB->getPointeeType();
6271 if (!Context.typesAreCompatible(
6272 Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6273 Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6274 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6275 << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
6276 << ArgB->getSourceRange();
6277 }
6278 }
6279
6280 // at least one argument should be pointer type
6281 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6282 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6283 << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6284
6285 if (isNull(ArgA)) // adopt type of the other pointer
6286 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6287
6288 if (isNull(ArgB))
6289 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6290
6291 TheCall->setArg(0, ArgExprA.get());
6292 TheCall->setArg(1, ArgExprB.get());
6293 TheCall->setType(Context.LongLongTy);
6294 return false;
6295 }
6296 assert(false && "Unhandled ARM MTE intrinsic");
6297 return true;
6298}
6299
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006300/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6301/// TheCall is an ARM/AArch64 special register string literal.
6302bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6303 int ArgNum, unsigned ExpectedFieldNum,
6304 bool AllowName) {
6305 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6306 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6307 BuiltinID == ARM::BI__builtin_arm_rsr ||
6308 BuiltinID == ARM::BI__builtin_arm_rsrp ||
6309 BuiltinID == ARM::BI__builtin_arm_wsr ||
6310 BuiltinID == ARM::BI__builtin_arm_wsrp;
6311 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6312 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6313 BuiltinID == AArch64::BI__builtin_arm_rsr ||
6314 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6315 BuiltinID == AArch64::BI__builtin_arm_wsr ||
6316 BuiltinID == AArch64::BI__builtin_arm_wsrp;
6317 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6318
6319 // We can't check the value of a dependent argument.
6320 Expr *Arg = TheCall->getArg(ArgNum);
6321 if (Arg->isTypeDependent() || Arg->isValueDependent())
6322 return false;
6323
6324 // Check if the argument is a string literal.
6325 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006326 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006327 << Arg->getSourceRange();
6328
6329 // Check the type of special register given.
6330 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6331 SmallVector<StringRef, 6> Fields;
6332 Reg.split(Fields, ":");
6333
6334 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006335 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006336 << Arg->getSourceRange();
6337
6338 // If the string is the name of a register then we cannot check that it is
6339 // valid here but if the string is of one the forms described in ACLE then we
6340 // can check that the supplied fields are integers and within the valid
6341 // ranges.
6342 if (Fields.size() > 1) {
6343 bool FiveFields = Fields.size() == 5;
6344
6345 bool ValidString = true;
6346 if (IsARMBuiltin) {
6347 ValidString &= Fields[0].startswith_lower("cp") ||
6348 Fields[0].startswith_lower("p");
6349 if (ValidString)
6350 Fields[0] =
6351 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6352
6353 ValidString &= Fields[2].startswith_lower("c");
6354 if (ValidString)
6355 Fields[2] = Fields[2].drop_front(1);
6356
6357 if (FiveFields) {
6358 ValidString &= Fields[3].startswith_lower("c");
6359 if (ValidString)
6360 Fields[3] = Fields[3].drop_front(1);
6361 }
6362 }
6363
6364 SmallVector<int, 5> Ranges;
6365 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00006366 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006367 else
6368 Ranges.append({15, 7, 15});
6369
6370 for (unsigned i=0; i<Fields.size(); ++i) {
6371 int IntField;
6372 ValidString &= !Fields[i].getAsInteger(10, IntField);
6373 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6374 }
6375
6376 if (!ValidString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006377 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006378 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006379 } else if (IsAArch64Builtin && Fields.size() == 1) {
6380 // If the register name is one of those that appear in the condition below
6381 // and the special register builtin being used is one of the write builtins,
6382 // then we require that the argument provided for writing to the register
6383 // is an integer constant expression. This is because it will be lowered to
6384 // an MSR (immediate) instruction, so we need to know the immediate at
6385 // compile time.
6386 if (TheCall->getNumArgs() != 2)
6387 return false;
6388
6389 std::string RegLower = Reg.lower();
6390 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6391 RegLower != "pan" && RegLower != "uao")
6392 return false;
6393
6394 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6395 }
6396
6397 return false;
6398}
6399
Eli Friedmanc97d0142009-05-03 06:04:26 +00006400/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006401/// This checks that the target supports __builtin_longjmp and
6402/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006403bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006404 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006405 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006406 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006407
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006408 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00006409 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00006410
Eric Christopher8d0c6212010-04-17 02:26:23 +00006411 // TODO: This is less than ideal. Overload this to take a value.
6412 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6413 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006414
Eric Christopher8d0c6212010-04-17 02:26:23 +00006415 if (Result != 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006416 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006417 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006418
6419 return false;
6420}
6421
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006422/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6423/// This checks that the target supports __builtin_setjmp.
6424bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6425 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006426 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006427 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006428 return false;
6429}
6430
Richard Smithd7293d72013-08-05 18:49:43 +00006431namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006432
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006433class UncoveredArgHandler {
6434 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006435
6436 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006437 SmallVector<const Expr *, 4> DiagnosticExprs;
6438
6439public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006440 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006441
6442 bool hasUncoveredArg() const {
6443 return (FirstUncoveredArg >= 0);
6444 }
6445
6446 unsigned getUncoveredArg() const {
6447 assert(hasUncoveredArg() && "no uncovered argument");
6448 return FirstUncoveredArg;
6449 }
6450
6451 void setAllCovered() {
6452 // A string has been found with all arguments covered, so clear out
6453 // the diagnostics.
6454 DiagnosticExprs.clear();
6455 FirstUncoveredArg = AllCovered;
6456 }
6457
6458 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6459 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6460
6461 // Don't update if a previous string covers all arguments.
6462 if (FirstUncoveredArg == AllCovered)
6463 return;
6464
6465 // UncoveredArgHandler tracks the highest uncovered argument index
6466 // and with it all the strings that match this index.
6467 if (NewFirstUncoveredArg == FirstUncoveredArg)
6468 DiagnosticExprs.push_back(StrExpr);
6469 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6470 DiagnosticExprs.clear();
6471 DiagnosticExprs.push_back(StrExpr);
6472 FirstUncoveredArg = NewFirstUncoveredArg;
6473 }
6474 }
6475
6476 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6477};
6478
Richard Smithd7293d72013-08-05 18:49:43 +00006479enum StringLiteralCheckType {
6480 SLCT_NotALiteral,
6481 SLCT_UncheckedLiteral,
6482 SLCT_CheckedLiteral
6483};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006484
6485} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00006486
Stephen Hines648c3692016-09-16 01:07:04 +00006487static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6488 BinaryOperatorKind BinOpKind,
6489 bool AddendIsRight) {
6490 unsigned BitWidth = Offset.getBitWidth();
6491 unsigned AddendBitWidth = Addend.getBitWidth();
6492 // There might be negative interim results.
6493 if (Addend.isUnsigned()) {
6494 Addend = Addend.zext(++AddendBitWidth);
6495 Addend.setIsSigned(true);
6496 }
6497 // Adjust the bit width of the APSInts.
6498 if (AddendBitWidth > BitWidth) {
6499 Offset = Offset.sext(AddendBitWidth);
6500 BitWidth = AddendBitWidth;
6501 } else if (BitWidth > AddendBitWidth) {
6502 Addend = Addend.sext(BitWidth);
6503 }
6504
6505 bool Ov = false;
6506 llvm::APSInt ResOffset = Offset;
6507 if (BinOpKind == BO_Add)
6508 ResOffset = Offset.sadd_ov(Addend, Ov);
6509 else {
6510 assert(AddendIsRight && BinOpKind == BO_Sub &&
6511 "operator must be add or sub with addend on the right");
6512 ResOffset = Offset.ssub_ov(Addend, Ov);
6513 }
6514
6515 // We add an offset to a pointer here so we should support an offset as big as
6516 // possible.
6517 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006518 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6519 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00006520 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00006521 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6522 return;
6523 }
6524
6525 Offset = ResOffset;
6526}
6527
6528namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006529
Stephen Hines648c3692016-09-16 01:07:04 +00006530// This is a wrapper class around StringLiteral to support offsetted string
6531// literals as format strings. It takes the offset into account when returning
6532// the string and its length or the source locations to display notes correctly.
6533class FormatStringLiteral {
6534 const StringLiteral *FExpr;
6535 int64_t Offset;
6536
6537 public:
6538 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6539 : FExpr(fexpr), Offset(Offset) {}
6540
6541 StringRef getString() const {
6542 return FExpr->getString().drop_front(Offset);
6543 }
6544
6545 unsigned getByteLength() const {
6546 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6547 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006548
Stephen Hines648c3692016-09-16 01:07:04 +00006549 unsigned getLength() const { return FExpr->getLength() - Offset; }
6550 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6551
6552 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6553
6554 QualType getType() const { return FExpr->getType(); }
6555
6556 bool isAscii() const { return FExpr->isAscii(); }
6557 bool isWide() const { return FExpr->isWide(); }
6558 bool isUTF8() const { return FExpr->isUTF8(); }
6559 bool isUTF16() const { return FExpr->isUTF16(); }
6560 bool isUTF32() const { return FExpr->isUTF32(); }
6561 bool isPascal() const { return FExpr->isPascal(); }
6562
6563 SourceLocation getLocationOfByte(
6564 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6565 const TargetInfo &Target, unsigned *StartToken = nullptr,
6566 unsigned *StartTokenByteOffset = nullptr) const {
6567 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6568 StartToken, StartTokenByteOffset);
6569 }
6570
Stephen Kelly724e9e52018-08-09 20:05:03 +00006571 SourceLocation getBeginLoc() const LLVM_READONLY {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006572 return FExpr->getBeginLoc().getLocWithOffset(Offset);
Stephen Hines648c3692016-09-16 01:07:04 +00006573 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006574
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006575 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
Stephen Hines648c3692016-09-16 01:07:04 +00006576};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006577
6578} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00006579
6580static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006581 const Expr *OrigFormatExpr,
6582 ArrayRef<const Expr *> Args,
6583 bool HasVAListArg, unsigned format_idx,
6584 unsigned firstDataArg,
6585 Sema::FormatStringType Type,
6586 bool inFunctionCall,
6587 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006588 llvm::SmallBitVector &CheckedVarArgs,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006589 UncoveredArgHandler &UncoveredArg,
6590 bool IgnoreStringsWithoutSpecifiers);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006591
Richard Smith55ce3522012-06-25 20:30:08 +00006592// Determine if an expression is a string literal or constant string.
6593// If this function returns false on the arguments to a function expecting a
6594// format string, we will usually need to emit a warning.
6595// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00006596static StringLiteralCheckType
6597checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6598 bool HasVAListArg, unsigned format_idx,
6599 unsigned firstDataArg, Sema::FormatStringType Type,
6600 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006601 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006602 UncoveredArgHandler &UncoveredArg,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006603 llvm::APSInt Offset,
6604 bool IgnoreStringsWithoutSpecifiers = false) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00006605 if (S.isConstantEvaluated())
6606 return SLCT_NotALiteral;
Ted Kremenek808829352010-09-09 03:51:39 +00006607 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00006608 assert(Offset.isSigned() && "invalid offset");
6609
Douglas Gregorc25f7662009-05-19 22:10:17 +00006610 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00006611 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006612
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006613 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00006614
Richard Smithd7293d72013-08-05 18:49:43 +00006615 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00006616 // Technically -Wformat-nonliteral does not warn about this case.
6617 // The behavior of printf and friends in this case is implementation
6618 // dependent. Ideally if the format string cannot be null then
6619 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00006620 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00006621
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006622 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00006623 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006624 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00006625 // The expression is a literal if both sub-expressions were, and it was
6626 // completely checked only if both sub-expressions were checked.
6627 const AbstractConditionalOperator *C =
6628 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006629
6630 // Determine whether it is necessary to check both sub-expressions, for
6631 // example, because the condition expression is a constant that can be
6632 // evaluated at compile time.
6633 bool CheckLeft = true, CheckRight = true;
6634
6635 bool Cond;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00006636 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6637 S.isConstantEvaluated())) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006638 if (Cond)
6639 CheckRight = false;
6640 else
6641 CheckLeft = false;
6642 }
6643
Stephen Hines648c3692016-09-16 01:07:04 +00006644 // We need to maintain the offsets for the right and the left hand side
6645 // separately to check if every possible indexed expression is a valid
6646 // string literal. They might have different offsets for different string
6647 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006648 StringLiteralCheckType Left;
6649 if (!CheckLeft)
6650 Left = SLCT_UncheckedLiteral;
6651 else {
6652 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6653 HasVAListArg, format_idx, firstDataArg,
6654 Type, CallType, InFunctionCall,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006655 CheckedVarArgs, UncoveredArg, Offset,
6656 IgnoreStringsWithoutSpecifiers);
Stephen Hines648c3692016-09-16 01:07:04 +00006657 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006658 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00006659 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006660 }
6661
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006662 StringLiteralCheckType Right = checkFormatStringExpr(
6663 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6664 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6665 IgnoreStringsWithoutSpecifiers);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006666
6667 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006668 }
6669
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006670 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00006671 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6672 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006673
John McCallc07a0c72011-02-17 10:25:35 +00006674 case Stmt::OpaqueValueExprClass:
6675 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6676 E = src;
6677 goto tryAgain;
6678 }
Richard Smith55ce3522012-06-25 20:30:08 +00006679 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00006680
Ted Kremeneka8890832011-02-24 23:03:04 +00006681 case Stmt::PredefinedExprClass:
6682 // While __func__, etc., are technically not string literals, they
6683 // cannot contain format specifiers and thus are not a security
6684 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00006685 return SLCT_UncheckedLiteral;
Fangrui Song6907ce22018-07-30 19:24:48 +00006686
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006687 case Stmt::DeclRefExprClass: {
6688 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006689
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006690 // As an exception, do not flag errors for variables binding to
6691 // const string literals.
6692 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6693 bool isConstant = false;
6694 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006695
Richard Smithd7293d72013-08-05 18:49:43 +00006696 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6697 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00006698 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00006699 isConstant = T.isConstant(S.Context) &&
6700 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00006701 } else if (T->isObjCObjectPointerType()) {
6702 // In ObjC, there is usually no "const ObjectPointer" type,
6703 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00006704 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006705 }
Mike Stump11289f42009-09-09 15:08:12 +00006706
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006707 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006708 if (const Expr *Init = VD->getAnyInitializer()) {
6709 // Look through initializers like const char c[] = { "foo" }
6710 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6711 if (InitList->isStringLiteralInit())
6712 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6713 }
Richard Smithd7293d72013-08-05 18:49:43 +00006714 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006715 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006716 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006717 /*InFunctionCall*/ false, CheckedVarArgs,
6718 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006719 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006720 }
Mike Stump11289f42009-09-09 15:08:12 +00006721
Anders Carlssonb012ca92009-06-28 19:55:58 +00006722 // For vprintf* functions (i.e., HasVAListArg==true), we add a
6723 // special check to see if the format string is a function parameter
6724 // of the function calling the printf function. If the function
6725 // has an attribute indicating it is a printf-like function, then we
6726 // should suppress warnings concerning non-literals being used in a call
6727 // to a vprintf function. For example:
6728 //
6729 // void
6730 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6731 // va_list ap;
6732 // va_start(ap, fmt);
6733 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
6734 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00006735 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006736 if (HasVAListArg) {
6737 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6738 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6739 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00006740 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006741 // adjust for implicit parameter
6742 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6743 if (MD->isInstance())
6744 ++PVIndex;
6745 // We also check if the formats are compatible.
6746 // We can't pass a 'scanf' string to a 'printf' function.
6747 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00006748 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00006749 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006750 }
6751 }
6752 }
6753 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006754 }
Mike Stump11289f42009-09-09 15:08:12 +00006755
Richard Smith55ce3522012-06-25 20:30:08 +00006756 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006757 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006758
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006759 case Stmt::CallExprClass:
6760 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006761 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006762 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
Michael Krusef18adbb2018-07-04 01:37:11 +00006763 bool IsFirst = true;
6764 StringLiteralCheckType CommonResult;
6765 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006766 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Michael Krusef18adbb2018-07-04 01:37:11 +00006767 StringLiteralCheckType Result = checkFormatStringExpr(
6768 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006769 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6770 IgnoreStringsWithoutSpecifiers);
Michael Krusef18adbb2018-07-04 01:37:11 +00006771 if (IsFirst) {
6772 CommonResult = Result;
6773 IsFirst = false;
6774 }
6775 }
6776 if (!IsFirst)
6777 return CommonResult;
6778
6779 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006780 unsigned BuiltinID = FD->getBuiltinID();
6781 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6782 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6783 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00006784 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006785 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006786 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006787 InFunctionCall, CheckedVarArgs,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006788 UncoveredArg, Offset,
6789 IgnoreStringsWithoutSpecifiers);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006790 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006791 }
6792 }
Mike Stump11289f42009-09-09 15:08:12 +00006793
Richard Smith55ce3522012-06-25 20:30:08 +00006794 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006795 }
Alex Lorenzd9007142016-10-24 09:42:34 +00006796 case Stmt::ObjCMessageExprClass: {
6797 const auto *ME = cast<ObjCMessageExpr>(E);
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006798 if (const auto *MD = ME->getMethodDecl()) {
6799 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6800 // As a special case heuristic, if we're using the method -[NSBundle
6801 // localizedStringForKey:value:table:], ignore any key strings that lack
6802 // format specifiers. The idea is that if the key doesn't have any
6803 // format specifiers then its probably just a key to map to the
6804 // localized strings. If it does have format specifiers though, then its
6805 // likely that the text of the key is the format string in the
6806 // programmer's language, and should be checked.
6807 const ObjCInterfaceDecl *IFace;
6808 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6809 IFace->getIdentifier()->isStr("NSBundle") &&
6810 MD->getSelector().isKeywordSelector(
6811 {"localizedStringForKey", "value", "table"})) {
6812 IgnoreStringsWithoutSpecifiers = true;
6813 }
6814
Joel E. Denny81508102018-03-13 14:51:22 +00006815 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00006816 return checkFormatStringExpr(
6817 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006818 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6819 IgnoreStringsWithoutSpecifiers);
Alex Lorenzd9007142016-10-24 09:42:34 +00006820 }
6821 }
6822
6823 return SLCT_NotALiteral;
6824 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006825 case Stmt::ObjCStringLiteralClass:
6826 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00006827 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006828
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006829 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006830 StrE = ObjCFExpr->getString();
6831 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006832 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006833
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006834 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00006835 if (Offset.isNegative() || Offset > StrE->getLength()) {
6836 // TODO: It would be better to have an explicit warning for out of
6837 // bounds literals.
6838 return SLCT_NotALiteral;
6839 }
6840 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6841 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006842 firstDataArg, Type, InFunctionCall, CallType,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00006843 CheckedVarArgs, UncoveredArg,
6844 IgnoreStringsWithoutSpecifiers);
Richard Smith55ce3522012-06-25 20:30:08 +00006845 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006846 }
Mike Stump11289f42009-09-09 15:08:12 +00006847
Richard Smith55ce3522012-06-25 20:30:08 +00006848 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006849 }
Stephen Hines648c3692016-09-16 01:07:04 +00006850 case Stmt::BinaryOperatorClass: {
Stephen Hines648c3692016-09-16 01:07:04 +00006851 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6852
6853 // A string literal + an int offset is still a string literal.
6854 if (BinOp->isAdditiveOp()) {
Fangrui Song407659a2018-11-30 23:41:18 +00006855 Expr::EvalResult LResult, RResult;
6856
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00006857 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6858 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6859 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6860 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
Stephen Hines648c3692016-09-16 01:07:04 +00006861
6862 if (LIsInt != RIsInt) {
6863 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6864
6865 if (LIsInt) {
6866 if (BinOpKind == BO_Add) {
Fangrui Song407659a2018-11-30 23:41:18 +00006867 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00006868 E = BinOp->getRHS();
6869 goto tryAgain;
6870 }
6871 } else {
Fangrui Song407659a2018-11-30 23:41:18 +00006872 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00006873 E = BinOp->getLHS();
6874 goto tryAgain;
6875 }
6876 }
Stephen Hines648c3692016-09-16 01:07:04 +00006877 }
George Burgess IVd273aab2016-09-22 00:00:26 +00006878
6879 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00006880 }
6881 case Stmt::UnaryOperatorClass: {
6882 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6883 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006884 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Fangrui Song407659a2018-11-30 23:41:18 +00006885 Expr::EvalResult IndexResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00006886 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6887 Expr::SE_NoSideEffects,
6888 S.isConstantEvaluated())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006889 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6890 /*RHS is int*/ true);
Stephen Hines648c3692016-09-16 01:07:04 +00006891 E = ASE->getBase();
6892 goto tryAgain;
6893 }
6894 }
6895
6896 return SLCT_NotALiteral;
6897 }
Mike Stump11289f42009-09-09 15:08:12 +00006898
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006899 default:
Richard Smith55ce3522012-06-25 20:30:08 +00006900 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006901 }
6902}
6903
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006904Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00006905 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00006906 .Case("scanf", FST_Scanf)
6907 .Cases("printf", "printf0", FST_Printf)
6908 .Cases("NSString", "CFString", FST_NSString)
6909 .Case("strftime", FST_Strftime)
6910 .Case("strfmon", FST_Strfmon)
6911 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6912 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6913 .Case("os_trace", FST_OSLog)
6914 .Case("os_log", FST_OSLog)
6915 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006916}
6917
Jordan Rose3e0ec582012-07-19 18:10:23 +00006918/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00006919/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00006920/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006921bool Sema::CheckFormatArguments(const FormatAttr *Format,
6922 ArrayRef<const Expr *> Args,
6923 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006924 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006925 SourceLocation Loc, SourceRange Range,
6926 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00006927 FormatStringInfo FSI;
6928 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006929 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00006930 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00006931 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00006932 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006933}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00006934
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006935bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006936 bool HasVAListArg, unsigned format_idx,
6937 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006938 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006939 SourceLocation Loc, SourceRange Range,
6940 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00006941 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006942 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006943 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00006944 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006945 }
Mike Stump11289f42009-09-09 15:08:12 +00006946
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006947 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006948
Chris Lattnerb87b1b32007-08-10 20:18:51 +00006949 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00006950 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006951 // Dynamically generated format strings are difficult to
6952 // automatically vet at compile time. Requiring that format strings
6953 // are string literals: (1) permits the checking of format strings by
6954 // the compiler and thereby (2) can practically remove the source of
6955 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00006956
Mike Stump11289f42009-09-09 15:08:12 +00006957 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00006958 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00006959 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00006960 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006961 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00006962 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00006963 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6964 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006965 /*IsFunctionCall*/ true, CheckedVarArgs,
6966 UncoveredArg,
6967 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006968
6969 // Generate a diagnostic where an uncovered argument is detected.
6970 if (UncoveredArg.hasUncoveredArg()) {
6971 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6972 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6973 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6974 }
6975
Richard Smith55ce3522012-06-25 20:30:08 +00006976 if (CT != SLCT_NotALiteral)
6977 // Literal format string found, check done!
6978 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00006979
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006980 // Strftime is particular as it always uses a single 'time' argument,
6981 // so it is safe to pass a non-literal string.
6982 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00006983 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006984
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006985 // Do not emit diag when the string param is a macro expansion and the
6986 // format is either NSString or CFString. This is a hack to prevent
6987 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6988 // which are usually used in place of NS and CF string literals.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006989 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006990 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00006991 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006992
Chris Lattnercc5d1c22009-04-29 04:59:47 +00006993 // If there are no arguments specified, warn with -Wformat-security, otherwise
6994 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006995 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00006996 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6997 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006998 switch (Type) {
6999 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007000 break;
7001 case FST_Kprintf:
7002 case FST_FreeBSDKPrintf:
7003 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00007004 Diag(FormatLoc, diag::note_format_security_fixit)
7005 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007006 break;
7007 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00007008 Diag(FormatLoc, diag::note_format_security_fixit)
7009 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007010 break;
7011 }
7012 } else {
7013 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00007014 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00007015 }
Richard Smith55ce3522012-06-25 20:30:08 +00007016 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00007017}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00007018
Ted Kremenekab278de2010-01-28 23:39:18 +00007019namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007020
Ted Kremenek02087932010-07-16 02:11:22 +00007021class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7022protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00007023 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00007024 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00007025 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00007026 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00007027 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00007028 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00007029 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00007030 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007031 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00007032 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00007033 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007034 bool usesPositionalArgs = false;
7035 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00007036 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00007037 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00007038 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007039 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007040
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007041public:
Stephen Hines648c3692016-09-16 01:07:04 +00007042 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007043 const Expr *origFormatExpr,
7044 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00007045 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007046 ArrayRef<const Expr *> Args, unsigned formatIdx,
7047 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007048 llvm::SmallBitVector &CheckedVarArgs,
7049 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007050 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7051 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7052 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00007053 inFunctionCall(inFunctionCall), CallType(callType),
7054 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00007055 CoveredArgs.resize(numDataArgs);
7056 CoveredArgs.reset();
7057 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007058
Ted Kremenek019d2242010-01-29 01:50:07 +00007059 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007060
Ted Kremenek02087932010-07-16 02:11:22 +00007061 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007062 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007063
Jordan Rose92303592012-09-08 04:00:03 +00007064 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00007065 const analyze_format_string::FormatSpecifier &FS,
7066 const analyze_format_string::ConversionSpecifier &CS,
7067 const char *startSpecifier, unsigned specifierLen,
7068 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00007069
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007070 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00007071 const analyze_format_string::FormatSpecifier &FS,
7072 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007073
7074 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00007075 const analyze_format_string::ConversionSpecifier &CS,
7076 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007077
Craig Toppere14c0f82014-03-12 04:55:44 +00007078 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00007079
Craig Toppere14c0f82014-03-12 04:55:44 +00007080 void HandleInvalidPosition(const char *startSpecifier,
7081 unsigned specifierLen,
7082 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00007083
Craig Toppere14c0f82014-03-12 04:55:44 +00007084 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00007085
Craig Toppere14c0f82014-03-12 04:55:44 +00007086 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007087
Richard Trieu03cf7b72011-10-28 00:41:25 +00007088 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00007089 static void
7090 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7091 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7092 bool IsStringLocation, Range StringRange,
7093 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00007094
Ted Kremenek02087932010-07-16 02:11:22 +00007095protected:
Ted Kremenekce815422010-07-19 21:25:57 +00007096 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7097 const char *startSpec,
7098 unsigned specifierLen,
7099 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00007100
7101 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7102 const char *startSpec,
7103 unsigned specifierLen);
Fangrui Song6907ce22018-07-30 19:24:48 +00007104
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007105 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00007106 CharSourceRange getSpecifierRange(const char *startSpecifier,
7107 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00007108 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007109
Ted Kremenek5739de72010-01-29 01:06:55 +00007110 const Expr *getDataArg(unsigned i) const;
Fangrui Song6907ce22018-07-30 19:24:48 +00007111
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007112 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7113 const analyze_format_string::ConversionSpecifier &CS,
7114 const char *startSpecifier, unsigned specifierLen,
7115 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00007116
7117 template <typename Range>
7118 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7119 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007120 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00007121};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007122
7123} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007124
Ted Kremenek02087932010-07-16 02:11:22 +00007125SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00007126 return OrigFormatExpr->getSourceRange();
7127}
7128
Ted Kremenek02087932010-07-16 02:11:22 +00007129CharSourceRange CheckFormatHandler::
7130getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00007131 SourceLocation Start = getLocationOfByte(startSpecifier);
7132 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7133
7134 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007135 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00007136
7137 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007138}
7139
Ted Kremenek02087932010-07-16 02:11:22 +00007140SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00007141 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7142 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00007143}
7144
Ted Kremenek02087932010-07-16 02:11:22 +00007145void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7146 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00007147 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7148 getLocationOfByte(startSpecifier),
7149 /*IsStringLocation*/true,
7150 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00007151}
7152
Jordan Rose92303592012-09-08 04:00:03 +00007153void CheckFormatHandler::HandleInvalidLengthModifier(
7154 const analyze_format_string::FormatSpecifier &FS,
7155 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00007156 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00007157 using namespace analyze_format_string;
7158
7159 const LengthModifier &LM = FS.getLengthModifier();
7160 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7161
7162 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00007163 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00007164 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00007165 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00007166 getLocationOfByte(LM.getStart()),
7167 /*IsStringLocation*/true,
7168 getSpecifierRange(startSpecifier, specifierLen));
7169
7170 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7171 << FixedLM->toString()
7172 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7173
7174 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00007175 FixItHint Hint;
7176 if (DiagID == diag::warn_format_nonsensical_length)
7177 Hint = FixItHint::CreateRemoval(LMRange);
7178
7179 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00007180 getLocationOfByte(LM.getStart()),
7181 /*IsStringLocation*/true,
7182 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00007183 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00007184 }
7185}
7186
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007187void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00007188 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007189 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00007190 using namespace analyze_format_string;
7191
7192 const LengthModifier &LM = FS.getLengthModifier();
7193 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7194
7195 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00007196 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00007197 if (FixedLM) {
7198 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7199 << LM.toString() << 0,
7200 getLocationOfByte(LM.getStart()),
7201 /*IsStringLocation*/true,
7202 getSpecifierRange(startSpecifier, specifierLen));
7203
7204 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7205 << FixedLM->toString()
7206 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7207
7208 } else {
7209 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7210 << LM.toString() << 0,
7211 getLocationOfByte(LM.getStart()),
7212 /*IsStringLocation*/true,
7213 getSpecifierRange(startSpecifier, specifierLen));
7214 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007215}
7216
7217void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7218 const analyze_format_string::ConversionSpecifier &CS,
7219 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00007220 using namespace analyze_format_string;
7221
7222 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00007223 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00007224 if (FixedCS) {
7225 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7226 << CS.toString() << /*conversion specifier*/1,
7227 getLocationOfByte(CS.getStart()),
7228 /*IsStringLocation*/true,
7229 getSpecifierRange(startSpecifier, specifierLen));
7230
7231 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7232 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7233 << FixedCS->toString()
7234 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7235 } else {
7236 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7237 << CS.toString() << /*conversion specifier*/1,
7238 getLocationOfByte(CS.getStart()),
7239 /*IsStringLocation*/true,
7240 getSpecifierRange(startSpecifier, specifierLen));
7241 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007242}
7243
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00007244void CheckFormatHandler::HandlePosition(const char *startPos,
7245 unsigned posLen) {
7246 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7247 getLocationOfByte(startPos),
7248 /*IsStringLocation*/true,
7249 getSpecifierRange(startPos, posLen));
7250}
7251
Ted Kremenekd1668192010-02-27 01:41:03 +00007252void
Ted Kremenek02087932010-07-16 02:11:22 +00007253CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7254 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007255 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7256 << (unsigned) p,
7257 getLocationOfByte(startPos), /*IsStringLocation*/true,
7258 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00007259}
7260
Ted Kremenek02087932010-07-16 02:11:22 +00007261void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00007262 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007263 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7264 getLocationOfByte(startPos),
7265 /*IsStringLocation*/true,
7266 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00007267}
7268
Ted Kremenek02087932010-07-16 02:11:22 +00007269void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00007270 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00007271 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00007272 EmitFormatDiagnostic(
7273 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7274 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7275 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00007276 }
Ted Kremenek02087932010-07-16 02:11:22 +00007277}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007278
Jordan Rose58bbe422012-07-19 18:10:08 +00007279// Note that this may return NULL if there was an error parsing or building
7280// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00007281const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007282 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00007283}
7284
7285void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007286 // Does the number of data arguments exceed the number of
7287 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00007288 if (!HasVAListArg) {
7289 // Find any arguments that weren't covered.
7290 CoveredArgs.flip();
7291 signed notCoveredArg = CoveredArgs.find_first();
7292 if (notCoveredArg >= 0) {
7293 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007294 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7295 } else {
7296 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00007297 }
7298 }
7299}
7300
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007301void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7302 const Expr *ArgExpr) {
7303 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7304 "Invalid state");
7305
7306 if (!ArgExpr)
7307 return;
7308
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007309 SourceLocation Loc = ArgExpr->getBeginLoc();
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007310
7311 if (S.getSourceManager().isInSystemMacro(Loc))
7312 return;
7313
7314 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7315 for (auto E : DiagnosticExprs)
7316 PDiag << E->getSourceRange();
7317
7318 CheckFormatHandler::EmitFormatDiagnostic(
7319 S, IsFunctionCall, DiagnosticExprs[0],
7320 PDiag, Loc, /*IsStringLocation*/false,
7321 DiagnosticExprs[0]->getSourceRange());
7322}
7323
Ted Kremenekce815422010-07-19 21:25:57 +00007324bool
7325CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7326 SourceLocation Loc,
7327 const char *startSpec,
7328 unsigned specifierLen,
7329 const char *csStart,
7330 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00007331 bool keepGoing = true;
7332 if (argIndex < NumDataArgs) {
7333 // Consider the argument coverered, even though the specifier doesn't
7334 // make sense.
7335 CoveredArgs.set(argIndex);
7336 }
7337 else {
7338 // If argIndex exceeds the number of data arguments we
7339 // don't issue a warning because that is just a cascade of warnings (and
7340 // they may have intended '%%' anyway). We don't want to continue processing
7341 // the format string after this point, however, as we will like just get
7342 // gibberish when trying to match arguments.
7343 keepGoing = false;
7344 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007345
7346 StringRef Specifier(csStart, csLen);
7347
7348 // If the specifier in non-printable, it could be the first byte of a UTF-8
7349 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7350 // hex value.
7351 std::string CodePointStr;
7352 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00007353 llvm::UTF32 CodePoint;
7354 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7355 const llvm::UTF8 *E =
7356 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7357 llvm::ConversionResult Result =
7358 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007359
Justin Lebar90910552016-09-30 00:38:45 +00007360 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007361 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00007362 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007363 }
7364
7365 llvm::raw_string_ostream OS(CodePointStr);
7366 if (CodePoint < 256)
7367 OS << "\\x" << llvm::format("%02x", CodePoint);
7368 else if (CodePoint <= 0xFFFF)
7369 OS << "\\u" << llvm::format("%04x", CodePoint);
7370 else
7371 OS << "\\U" << llvm::format("%08x", CodePoint);
7372 OS.flush();
7373 Specifier = CodePointStr;
7374 }
7375
7376 EmitFormatDiagnostic(
7377 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7378 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7379
Ted Kremenekce815422010-07-19 21:25:57 +00007380 return keepGoing;
7381}
7382
Richard Trieu03cf7b72011-10-28 00:41:25 +00007383void
7384CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7385 const char *startSpec,
7386 unsigned specifierLen) {
7387 EmitFormatDiagnostic(
7388 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7389 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7390}
7391
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007392bool
7393CheckFormatHandler::CheckNumArgs(
7394 const analyze_format_string::FormatSpecifier &FS,
7395 const analyze_format_string::ConversionSpecifier &CS,
7396 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7397
7398 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007399 PartialDiagnostic PDiag = FS.usesPositionalArg()
7400 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7401 << (argIndex+1) << NumDataArgs)
7402 : S.PDiag(diag::warn_printf_insufficient_data_args);
7403 EmitFormatDiagnostic(
7404 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7405 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007406
7407 // Since more arguments than conversion tokens are given, by extension
7408 // all arguments are covered, so mark this as so.
7409 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007410 return false;
7411 }
7412 return true;
7413}
7414
Richard Trieu03cf7b72011-10-28 00:41:25 +00007415template<typename Range>
7416void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7417 SourceLocation Loc,
7418 bool IsStringLocation,
7419 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00007420 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007421 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00007422 Loc, IsStringLocation, StringRange, FixIt);
7423}
7424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007425/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00007426/// so that the function call and string are in diagnostic messages.
7427///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007428/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00007429/// call and only one diagnostic message will be produced. Otherwise, an
7430/// extra note will be emitted pointing to location of the format string.
7431///
7432/// \param ArgumentExpr the expression that is passed as the format string
7433/// argument in the function call. Used for getting locations when two
7434/// diagnostics are emitted.
7435///
7436/// \param PDiag the callee should already have provided any strings for the
7437/// diagnostic message. This function only adds locations and fixits
7438/// to diagnostics.
7439///
7440/// \param Loc primary location for diagnostic. If two diagnostics are
7441/// required, one will be at Loc and a new SourceLocation will be created for
7442/// the other one.
7443///
7444/// \param IsStringLocation if true, Loc points to the format string should be
7445/// used for the note. Otherwise, Loc points to the argument list and will
7446/// be used with PDiag.
7447///
7448/// \param StringRange some or all of the string to highlight. This is
7449/// templated so it can accept either a CharSourceRange or a SourceRange.
7450///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007451/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00007452template <typename Range>
7453void CheckFormatHandler::EmitFormatDiagnostic(
7454 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7455 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7456 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00007457 if (InFunctionCall) {
7458 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7459 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007460 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00007461 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007462 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7463 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00007464
7465 const Sema::SemaDiagnosticBuilder &Note =
7466 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7467 diag::note_format_string_defined);
7468
7469 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007470 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00007471 }
7472}
7473
Ted Kremenek02087932010-07-16 02:11:22 +00007474//===--- CHECK: Printf format string checking ------------------------------===//
7475
7476namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007477
Ted Kremenek02087932010-07-16 02:11:22 +00007478class CheckPrintfHandler : public CheckFormatHandler {
7479public:
Stephen Hines648c3692016-09-16 01:07:04 +00007480 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007481 const Expr *origFormatExpr,
7482 const Sema::FormatStringType type, unsigned firstDataArg,
7483 unsigned numDataArgs, bool isObjC, const char *beg,
7484 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00007485 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00007486 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007487 llvm::SmallBitVector &CheckedVarArgs,
7488 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007489 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7490 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7491 inFunctionCall, CallType, CheckedVarArgs,
7492 UncoveredArg) {}
7493
7494 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7495
7496 /// Returns true if '%@' specifiers are allowed in the format string.
7497 bool allowsObjCArg() const {
7498 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7499 FSType == Sema::FST_OSTrace;
7500 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00007501
Ted Kremenek02087932010-07-16 02:11:22 +00007502 bool HandleInvalidPrintfConversionSpecifier(
7503 const analyze_printf::PrintfSpecifier &FS,
7504 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007505 unsigned specifierLen) override;
7506
Akira Hatanakad572cf42018-11-06 07:05:14 +00007507 void handleInvalidMaskType(StringRef MaskType) override;
7508
Ted Kremenek02087932010-07-16 02:11:22 +00007509 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7510 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007511 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007512 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7513 const char *StartSpecifier,
7514 unsigned SpecifierLen,
7515 const Expr *E);
7516
Ted Kremenek02087932010-07-16 02:11:22 +00007517 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7518 const char *startSpecifier, unsigned specifierLen);
7519 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7520 const analyze_printf::OptionalAmount &Amt,
7521 unsigned type,
7522 const char *startSpecifier, unsigned specifierLen);
7523 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7524 const analyze_printf::OptionalFlag &flag,
7525 const char *startSpecifier, unsigned specifierLen);
7526 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7527 const analyze_printf::OptionalFlag &ignoredFlag,
7528 const analyze_printf::OptionalFlag &flag,
7529 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007530 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00007531 const Expr *E);
Fangrui Song6907ce22018-07-30 19:24:48 +00007532
Ted Kremenek2b417712015-07-02 05:39:16 +00007533 void HandleEmptyObjCModifierFlag(const char *startFlag,
7534 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007535
Ted Kremenek2b417712015-07-02 05:39:16 +00007536 void HandleInvalidObjCModifierFlag(const char *startFlag,
7537 unsigned flagLen) override;
7538
7539 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7540 const char *flagsEnd,
Fangrui Song6907ce22018-07-30 19:24:48 +00007541 const char *conversionPosition)
Ted Kremenek2b417712015-07-02 05:39:16 +00007542 override;
7543};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007544
7545} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00007546
7547bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7548 const analyze_printf::PrintfSpecifier &FS,
7549 const char *startSpecifier,
7550 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007551 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007552 FS.getConversionSpecifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00007553
Ted Kremenekce815422010-07-19 21:25:57 +00007554 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7555 getLocationOfByte(CS.getStart()),
7556 startSpecifier, specifierLen,
7557 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00007558}
7559
Akira Hatanakad572cf42018-11-06 07:05:14 +00007560void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7561 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7562}
7563
Ted Kremenek02087932010-07-16 02:11:22 +00007564bool CheckPrintfHandler::HandleAmount(
7565 const analyze_format_string::OptionalAmount &Amt,
7566 unsigned k, const char *startSpecifier,
7567 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007568 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007569 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00007570 unsigned argIndex = Amt.getArgIndex();
7571 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007572 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7573 << k,
7574 getLocationOfByte(Amt.getStart()),
7575 /*IsStringLocation*/true,
7576 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007577 // Don't do any more checking. We will just emit
7578 // spurious errors.
7579 return false;
7580 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007581
Ted Kremenek5739de72010-01-29 01:06:55 +00007582 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00007583 // Although not in conformance with C99, we also allow the argument to be
7584 // an 'unsigned int' as that is a reasonably safe case. GCC also
7585 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00007586 CoveredArgs.set(argIndex);
7587 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007588 if (!Arg)
7589 return false;
7590
Ted Kremenek5739de72010-01-29 01:06:55 +00007591 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007592
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007593 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7594 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007595
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007596 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007597 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007598 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00007599 << T << Arg->getSourceRange(),
7600 getLocationOfByte(Amt.getStart()),
7601 /*IsStringLocation*/true,
7602 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007603 // Don't do any more checking. We will just emit
7604 // spurious errors.
7605 return false;
7606 }
7607 }
7608 }
7609 return true;
7610}
Ted Kremenek5739de72010-01-29 01:06:55 +00007611
Tom Careb49ec692010-06-17 19:00:27 +00007612void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00007613 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007614 const analyze_printf::OptionalAmount &Amt,
7615 unsigned type,
7616 const char *startSpecifier,
7617 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007618 const analyze_printf::PrintfConversionSpecifier &CS =
7619 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00007620
Richard Trieu03cf7b72011-10-28 00:41:25 +00007621 FixItHint fixit =
7622 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7623 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7624 Amt.getConstantLength()))
7625 : FixItHint();
7626
7627 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7628 << type << CS.toString(),
7629 getLocationOfByte(Amt.getStart()),
7630 /*IsStringLocation*/true,
7631 getSpecifierRange(startSpecifier, specifierLen),
7632 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00007633}
7634
Ted Kremenek02087932010-07-16 02:11:22 +00007635void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007636 const analyze_printf::OptionalFlag &flag,
7637 const char *startSpecifier,
7638 unsigned specifierLen) {
7639 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007640 const analyze_printf::PrintfConversionSpecifier &CS =
7641 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00007642 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7643 << flag.toString() << CS.toString(),
7644 getLocationOfByte(flag.getPosition()),
7645 /*IsStringLocation*/true,
7646 getSpecifierRange(startSpecifier, specifierLen),
7647 FixItHint::CreateRemoval(
7648 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007649}
7650
7651void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00007652 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007653 const analyze_printf::OptionalFlag &ignoredFlag,
7654 const analyze_printf::OptionalFlag &flag,
7655 const char *startSpecifier,
7656 unsigned specifierLen) {
7657 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00007658 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7659 << ignoredFlag.toString() << flag.toString(),
7660 getLocationOfByte(ignoredFlag.getPosition()),
7661 /*IsStringLocation*/true,
7662 getSpecifierRange(startSpecifier, specifierLen),
7663 FixItHint::CreateRemoval(
7664 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007665}
7666
Ted Kremenek2b417712015-07-02 05:39:16 +00007667void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7668 unsigned flagLen) {
7669 // Warn about an empty flag.
7670 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7671 getLocationOfByte(startFlag),
7672 /*IsStringLocation*/true,
7673 getSpecifierRange(startFlag, flagLen));
7674}
7675
7676void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7677 unsigned flagLen) {
7678 // Warn about an invalid flag.
7679 auto Range = getSpecifierRange(startFlag, flagLen);
7680 StringRef flag(startFlag, flagLen);
7681 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7682 getLocationOfByte(startFlag),
7683 /*IsStringLocation*/true,
7684 Range, FixItHint::CreateRemoval(Range));
7685}
7686
7687void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7688 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7689 // Warn about using '[...]' without a '@' conversion.
7690 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7691 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7692 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7693 getLocationOfByte(conversionPosition),
7694 /*IsStringLocation*/true,
7695 Range, FixItHint::CreateRemoval(Range));
7696}
7697
Richard Smith55ce3522012-06-25 20:30:08 +00007698// Determines if the specified is a C++ class or struct containing
7699// a member with the specified name and kind (e.g. a CXXMethodDecl named
7700// "c_str()").
7701template<typename MemberKind>
7702static llvm::SmallPtrSet<MemberKind*, 1>
7703CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7704 const RecordType *RT = Ty->getAs<RecordType>();
7705 llvm::SmallPtrSet<MemberKind*, 1> Results;
7706
7707 if (!RT)
7708 return Results;
7709 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00007710 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00007711 return Results;
7712
Alp Tokerb6cc5922014-05-03 03:45:55 +00007713 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00007714 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00007715 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00007716
7717 // We just need to include all members of the right kind turned up by the
7718 // filter, at this point.
7719 if (S.LookupQualifiedName(R, RT->getDecl()))
7720 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7721 NamedDecl *decl = (*I)->getUnderlyingDecl();
7722 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7723 Results.insert(FK);
7724 }
7725 return Results;
7726}
7727
Richard Smith2868a732014-02-28 01:36:39 +00007728/// Check if we could call '.c_str()' on an object.
7729///
7730/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7731/// allow the call, or if it would be ambiguous).
7732bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007733 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7734
Richard Smith2868a732014-02-28 01:36:39 +00007735 MethodSet Results =
7736 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7737 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7738 MI != ME; ++MI)
7739 if ((*MI)->getMinRequiredArguments() == 0)
7740 return true;
7741 return false;
7742}
7743
Richard Smith55ce3522012-06-25 20:30:08 +00007744// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007745// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00007746// Returns true when a c_str() conversion method is found.
7747bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00007748 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007749 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00007750
7751 MethodSet Results =
7752 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7753
7754 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7755 MI != ME; ++MI) {
7756 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00007757 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00007758 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00007759 // FIXME: Suggest parens if the expression needs them.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007760 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007761 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7762 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
Richard Smith55ce3522012-06-25 20:30:08 +00007763 return true;
7764 }
7765 }
7766
7767 return false;
7768}
7769
Ted Kremenekab278de2010-01-28 23:39:18 +00007770bool
Ted Kremenek02087932010-07-16 02:11:22 +00007771CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00007772 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00007773 const char *startSpecifier,
7774 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007775 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007776 using namespace analyze_printf;
7777
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007778 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00007779
Ted Kremenek6cd69422010-07-19 22:01:06 +00007780 if (FS.consumesDataArgument()) {
7781 if (atFirstArg) {
7782 atFirstArg = false;
7783 usesPositionalArgs = FS.usesPositionalArg();
7784 }
7785 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007786 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7787 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007788 return false;
7789 }
Ted Kremenek5739de72010-01-29 01:06:55 +00007790 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007791
Ted Kremenekd1668192010-02-27 01:41:03 +00007792 // First check if the field width, precision, and conversion specifier
7793 // have matching data arguments.
7794 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7795 startSpecifier, specifierLen)) {
7796 return false;
7797 }
7798
7799 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7800 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007801 return false;
7802 }
7803
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007804 if (!CS.consumesDataArgument()) {
7805 // FIXME: Technically specifying a precision or field width here
7806 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00007807 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007808 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007809
Ted Kremenek4a49d982010-02-26 19:18:41 +00007810 // Consume the argument.
7811 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00007812 if (argIndex < NumDataArgs) {
7813 // The check to see if the argIndex is valid will come later.
7814 // We set the bit here because we may exit early from this
7815 // function if we encounter some other error.
7816 CoveredArgs.set(argIndex);
7817 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00007818
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007819 // FreeBSD kernel extensions.
7820 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7821 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7822 // We need at least two arguments.
7823 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7824 return false;
7825
7826 // Claim the second argument.
7827 CoveredArgs.set(argIndex + 1);
7828
7829 // Type check the first argument (int for %b, pointer for %D)
7830 const Expr *Ex = getDataArg(argIndex);
7831 const analyze_printf::ArgType &AT =
7832 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7833 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7834 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7835 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007836 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7837 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7838 << false << Ex->getSourceRange(),
7839 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7840 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007841
7842 // Type check the second argument (char * for both %b and %D)
7843 Ex = getDataArg(argIndex + 1);
7844 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7845 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7846 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007847 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7848 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7849 << false << Ex->getSourceRange(),
7850 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7851 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007852
7853 return true;
7854 }
7855
Ted Kremenek4a49d982010-02-26 19:18:41 +00007856 // Check for using an Objective-C specific conversion specifier
7857 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00007858 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00007859 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7860 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00007861 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007862
Mehdi Amini06d367c2016-10-24 20:39:34 +00007863 // %P can only be used with os_log.
7864 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7865 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7866 specifierLen);
7867 }
7868
7869 // %n is not allowed with os_log.
7870 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7871 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7872 getLocationOfByte(CS.getStart()),
7873 /*IsStringLocation*/ false,
7874 getSpecifierRange(startSpecifier, specifierLen));
7875
7876 return true;
7877 }
7878
7879 // Only scalars are allowed for os_trace.
7880 if (FSType == Sema::FST_OSTrace &&
7881 (CS.getKind() == ConversionSpecifier::PArg ||
7882 CS.getKind() == ConversionSpecifier::sArg ||
7883 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7884 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7885 specifierLen);
7886 }
7887
7888 // Check for use of public/private annotation outside of os_log().
7889 if (FSType != Sema::FST_OSLog) {
7890 if (FS.isPublic().isSet()) {
7891 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7892 << "public",
7893 getLocationOfByte(FS.isPublic().getPosition()),
7894 /*IsStringLocation*/ false,
7895 getSpecifierRange(startSpecifier, specifierLen));
7896 }
7897 if (FS.isPrivate().isSet()) {
7898 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7899 << "private",
7900 getLocationOfByte(FS.isPrivate().getPosition()),
7901 /*IsStringLocation*/ false,
7902 getSpecifierRange(startSpecifier, specifierLen));
7903 }
7904 }
7905
Tom Careb49ec692010-06-17 19:00:27 +00007906 // Check for invalid use of field width
7907 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00007908 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00007909 startSpecifier, specifierLen);
7910 }
7911
7912 // Check for invalid use of precision
7913 if (!FS.hasValidPrecision()) {
7914 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7915 startSpecifier, specifierLen);
7916 }
7917
Mehdi Amini06d367c2016-10-24 20:39:34 +00007918 // Precision is mandatory for %P specifier.
7919 if (CS.getKind() == ConversionSpecifier::PArg &&
7920 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7921 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7922 getLocationOfByte(startSpecifier),
7923 /*IsStringLocation*/ false,
7924 getSpecifierRange(startSpecifier, specifierLen));
7925 }
7926
Tom Careb49ec692010-06-17 19:00:27 +00007927 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00007928 if (!FS.hasValidThousandsGroupingPrefix())
7929 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007930 if (!FS.hasValidLeadingZeros())
7931 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7932 if (!FS.hasValidPlusPrefix())
7933 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00007934 if (!FS.hasValidSpacePrefix())
7935 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007936 if (!FS.hasValidAlternativeForm())
7937 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7938 if (!FS.hasValidLeftJustified())
7939 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7940
7941 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00007942 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7943 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7944 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007945 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7946 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7947 startSpecifier, specifierLen);
7948
7949 // Check the length modifier is valid with the given conversion specifier.
Matt Arsenault58fc8082019-01-29 20:49:54 +00007950 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7951 S.getLangOpts()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007952 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7953 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007954 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007955 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007956 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007957 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7958 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00007959
Jordan Rose92303592012-09-08 04:00:03 +00007960 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7961 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7962
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007963 // The remaining checks depend on the data arguments.
7964 if (HasVAListArg)
7965 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007966
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007967 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007968 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007969
Jordan Rose58bbe422012-07-19 18:10:08 +00007970 const Expr *Arg = getDataArg(argIndex);
7971 if (!Arg)
7972 return true;
7973
7974 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00007975}
7976
Jordan Roseaee34382012-09-05 22:56:26 +00007977static bool requiresParensToAddCast(const Expr *E) {
7978 // FIXME: We should have a general way to reason about operator
7979 // precedence and whether parens are actually needed here.
7980 // Take care of a few common cases where they aren't.
7981 const Expr *Inside = E->IgnoreImpCasts();
7982 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7983 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7984
7985 switch (Inside->getStmtClass()) {
7986 case Stmt::ArraySubscriptExprClass:
7987 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007988 case Stmt::CharacterLiteralClass:
7989 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007990 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007991 case Stmt::FloatingLiteralClass:
7992 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007993 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007994 case Stmt::ObjCArrayLiteralClass:
7995 case Stmt::ObjCBoolLiteralExprClass:
7996 case Stmt::ObjCBoxedExprClass:
7997 case Stmt::ObjCDictionaryLiteralClass:
7998 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007999 case Stmt::ObjCIvarRefExprClass:
8000 case Stmt::ObjCMessageExprClass:
8001 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00008002 case Stmt::ObjCStringLiteralClass:
8003 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00008004 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00008005 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00008006 case Stmt::UnaryOperatorClass:
8007 return false;
8008 default:
8009 return true;
8010 }
8011}
8012
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008013static std::pair<QualType, StringRef>
8014shouldNotPrintDirectly(const ASTContext &Context,
8015 QualType IntendedTy,
8016 const Expr *E) {
8017 // Use a 'while' to peel off layers of typedefs.
8018 QualType TyTy = IntendedTy;
8019 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8020 StringRef Name = UserTy->getDecl()->getName();
8021 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00008022 .Case("CFIndex", Context.getNSIntegerType())
8023 .Case("NSInteger", Context.getNSIntegerType())
8024 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008025 .Case("SInt32", Context.IntTy)
8026 .Case("UInt32", Context.UnsignedIntTy)
8027 .Default(QualType());
8028
8029 if (!CastTy.isNull())
8030 return std::make_pair(CastTy, Name);
8031
8032 TyTy = UserTy->desugar();
8033 }
8034
8035 // Strip parens if necessary.
8036 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8037 return shouldNotPrintDirectly(Context,
8038 PE->getSubExpr()->getType(),
8039 PE->getSubExpr());
8040
8041 // If this is a conditional expression, then its result type is constructed
8042 // via usual arithmetic conversions and thus there might be no necessary
8043 // typedef sugar there. Recurse to operands to check for NSInteger &
8044 // Co. usage condition.
8045 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8046 QualType TrueTy, FalseTy;
8047 StringRef TrueName, FalseName;
8048
8049 std::tie(TrueTy, TrueName) =
8050 shouldNotPrintDirectly(Context,
8051 CO->getTrueExpr()->getType(),
8052 CO->getTrueExpr());
8053 std::tie(FalseTy, FalseName) =
8054 shouldNotPrintDirectly(Context,
8055 CO->getFalseExpr()->getType(),
8056 CO->getFalseExpr());
8057
8058 if (TrueTy == FalseTy)
8059 return std::make_pair(TrueTy, TrueName);
8060 else if (TrueTy.isNull())
8061 return std::make_pair(FalseTy, FalseName);
8062 else if (FalseTy.isNull())
8063 return std::make_pair(TrueTy, TrueName);
8064 }
8065
8066 return std::make_pair(QualType(), StringRef());
8067}
8068
Aaron Ballman94d2d092018-12-18 15:54:38 +00008069/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8070/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8071/// type do not count.
8072static bool
8073isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8074 QualType From = ICE->getSubExpr()->getType();
8075 QualType To = ICE->getType();
8076 // It's an integer promotion if the destination type is the promoted
8077 // source type.
8078 if (ICE->getCastKind() == CK_IntegralCast &&
8079 From->isPromotableIntegerType() &&
8080 S.Context.getPromotedIntegerType(From) == To)
8081 return true;
8082 // Look through vector types, since we do default argument promotion for
8083 // those in OpenCL.
8084 if (const auto *VecTy = From->getAs<ExtVectorType>())
8085 From = VecTy->getElementType();
8086 if (const auto *VecTy = To->getAs<ExtVectorType>())
8087 To = VecTy->getElementType();
8088 // It's a floating promotion if the source type is a lower rank.
8089 return ICE->getCastKind() == CK_FloatingCast &&
8090 S.Context.getFloatingTypeOrder(From, To) < 0;
8091}
8092
Richard Smith55ce3522012-06-25 20:30:08 +00008093bool
8094CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8095 const char *StartSpecifier,
8096 unsigned SpecifierLen,
8097 const Expr *E) {
8098 using namespace analyze_format_string;
8099 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008100
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008101 // Now type check the data expression that matches the
8102 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00008103 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00008104 if (!AT.isValid())
8105 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00008106
Jordan Rose598ec092012-12-05 18:44:40 +00008107 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00008108 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8109 ExprTy = TET->getUnderlyingExpr()->getType();
8110 }
8111
JF Bastienec7d7f32018-06-22 21:54:40 +00008112 const analyze_printf::ArgType::MatchKind Match =
8113 AT.matchesType(S.Context, ExprTy);
8114 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
8115 if (Match == analyze_printf::ArgType::Match)
Jordan Rose22b74712012-09-05 22:56:19 +00008116 return true;
Jordan Rose98709982012-06-04 22:48:57 +00008117
Jordan Rose22b74712012-09-05 22:56:19 +00008118 // Look through argument promotions for our error message's reported type.
8119 // This includes the integral and floating promotions, but excludes array
Aaron Ballman94d2d092018-12-18 15:54:38 +00008120 // and function pointer decay (seeing that an argument intended to be a
8121 // string has type 'char [6]' is probably more confusing than 'char *') and
8122 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
Jordan Rose22b74712012-09-05 22:56:19 +00008123 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Aaron Ballman94d2d092018-12-18 15:54:38 +00008124 if (isArithmeticArgumentPromotion(S, ICE)) {
Jordan Rose22b74712012-09-05 22:56:19 +00008125 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00008126 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00008127
8128 // Check if we didn't match because of an implicit cast from a 'char'
8129 // or 'short' to an 'int'. This is done because printf is a varargs
8130 // function.
8131 if (ICE->getType() == S.Context.IntTy ||
8132 ICE->getType() == S.Context.UnsignedIntTy) {
Nathan Huckleberrycc01d642019-08-23 18:01:57 +00008133 // All further checking is done on the subexpression
8134 const analyze_printf::ArgType::MatchKind ImplicitMatch =
8135 AT.matchesType(S.Context, ExprTy);
8136 if (ImplicitMatch == analyze_printf::ArgType::Match)
Jordan Rose22b74712012-09-05 22:56:19 +00008137 return true;
Nathan Huckleberrycc01d642019-08-23 18:01:57 +00008138 if (ImplicitMatch == analyze_printf::ArgType::NoMatchPedantic)
8139 Pedantic = true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00008140 }
Jordan Rose98709982012-06-04 22:48:57 +00008141 }
Jordan Rose598ec092012-12-05 18:44:40 +00008142 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8143 // Special case for 'a', which has type 'int' in C.
8144 // Note, however, that we do /not/ want to treat multibyte constants like
8145 // 'MooV' as characters! This form is deprecated but still exists.
8146 if (ExprTy == S.Context.IntTy)
8147 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8148 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00008149 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008150
Jordan Rosebc53ed12014-05-31 04:12:14 +00008151 // Look through enums to their underlying type.
8152 bool IsEnum = false;
8153 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8154 ExprTy = EnumTy->getDecl()->getIntegerType();
8155 IsEnum = true;
8156 }
8157
Jordan Rose0e5badd2012-12-05 18:44:49 +00008158 // %C in an Objective-C context prints a unichar, not a wchar_t.
8159 // If the argument is an integer of some kind, believe the %C and suggest
8160 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00008161 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00008162 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00008163 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8164 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8165 !ExprTy->isCharType()) {
8166 // 'unichar' is defined as a typedef of unsigned short, but we should
8167 // prefer using the typedef if it is visible.
8168 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00008169
8170 // While we are here, check if the value is an IntegerLiteral that happens
8171 // to be within the valid range.
8172 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8173 const llvm::APInt &V = IL->getValue();
8174 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8175 return true;
8176 }
8177
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008178 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
Jordan Rose0e5badd2012-12-05 18:44:49 +00008179 Sema::LookupOrdinaryName);
8180 if (S.LookupName(Result, S.getCurScope())) {
8181 NamedDecl *ND = Result.getFoundDecl();
8182 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8183 if (TD->getUnderlyingType() == IntendedTy)
8184 IntendedTy = S.Context.getTypedefType(TD);
8185 }
8186 }
8187 }
8188
8189 // Special-case some of Darwin's platform-independence types by suggesting
8190 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008191 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00008192 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008193 QualType CastTy;
8194 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8195 if (!CastTy.isNull()) {
Alex Lorenzb2043ac2018-07-05 22:51:11 +00008196 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
JF Bastienec7d7f32018-06-22 21:54:40 +00008197 // (long in ASTContext). Only complain to pedants.
8198 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
Alex Lorenzb2043ac2018-07-05 22:51:11 +00008199 (AT.isSizeT() || AT.isPtrdiffT()) &&
8200 AT.matchesType(S.Context, CastTy))
JF Bastienec7d7f32018-06-22 21:54:40 +00008201 Pedantic = true;
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008202 IntendedTy = CastTy;
8203 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00008204 }
8205 }
8206
Jordan Rose22b74712012-09-05 22:56:19 +00008207 // We may be able to offer a FixItHint if it is a supported type.
8208 PrintfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00008209 bool Success =
Mehdi Amini06d367c2016-10-24 20:39:34 +00008210 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008211
JF Bastienec7d7f32018-06-22 21:54:40 +00008212 if (Success) {
Jordan Rose22b74712012-09-05 22:56:19 +00008213 // Get the fix string from the fixed format specifier
8214 SmallString<16> buf;
8215 llvm::raw_svector_ostream os(buf);
8216 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008217
Jordan Roseaee34382012-09-05 22:56:26 +00008218 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8219
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008220 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
JF Bastienec7d7f32018-06-22 21:54:40 +00008221 unsigned Diag =
8222 Pedantic
8223 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8224 : diag::warn_format_conversion_argument_type_mismatch;
Jordan Rose0e5badd2012-12-05 18:44:49 +00008225 // In this case, the specifier is wrong and should be changed to match
8226 // the argument.
JF Bastienec7d7f32018-06-22 21:54:40 +00008227 EmitFormatDiagnostic(S.PDiag(Diag)
Daniel Jasperad8d8492015-03-04 14:18:20 +00008228 << AT.getRepresentativeTypeName(S.Context)
8229 << IntendedTy << IsEnum << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008230 E->getBeginLoc(),
Daniel Jasperad8d8492015-03-04 14:18:20 +00008231 /*IsStringLocation*/ false, SpecRange,
8232 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00008233 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00008234 // The canonical type for formatting this value is different from the
8235 // actual type of the expression. (This occurs, for example, with Darwin's
8236 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8237 // should be printed as 'long' for 64-bit compatibility.)
8238 // Rather than emitting a normal format/argument mismatch, we want to
8239 // add a cast to the recommended type (and correct the format string
8240 // if necessary).
8241 SmallString<16> CastBuf;
8242 llvm::raw_svector_ostream CastFix(CastBuf);
8243 CastFix << "(";
8244 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8245 CastFix << ")";
8246
8247 SmallVector<FixItHint,4> Hints;
Fangrui Song6907ce22018-07-30 19:24:48 +00008248 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00008249 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8250
8251 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8252 // If there's already a cast present, just replace it.
8253 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8254 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8255
8256 } else if (!requiresParensToAddCast(E)) {
8257 // If the expression has high enough precedence,
8258 // just write the C-style cast.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008259 Hints.push_back(
8260 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00008261 } else {
8262 // Otherwise, add parens around the expression as well as the cast.
8263 CastFix << "(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008264 Hints.push_back(
8265 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00008266
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008267 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
Jordan Roseaee34382012-09-05 22:56:26 +00008268 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8269 }
8270
Jordan Rose0e5badd2012-12-05 18:44:49 +00008271 if (ShouldNotPrintDirectly) {
8272 // The expression has a type that should not be printed directly.
8273 // We extract the name from the typedef because we don't want to show
8274 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00008275 StringRef Name;
8276 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8277 Name = TypedefTy->getDecl()->getName();
8278 else
8279 Name = CastTyName;
JF Bastienec7d7f32018-06-22 21:54:40 +00008280 unsigned Diag = Pedantic
8281 ? diag::warn_format_argument_needs_cast_pedantic
8282 : diag::warn_format_argument_needs_cast;
8283 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8284 << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008285 E->getBeginLoc(), /*IsStringLocation=*/false,
Jordan Rose0e5badd2012-12-05 18:44:49 +00008286 SpecRange, Hints);
8287 } else {
8288 // In this case, the expression could be printed using a different
Fangrui Song6907ce22018-07-30 19:24:48 +00008289 // specifier, but we've decided that the specifier is probably correct
Jordan Rose0e5badd2012-12-05 18:44:49 +00008290 // and we should cast instead. Just use the normal warning message.
8291 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008292 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8293 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8294 << E->getSourceRange(),
8295 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
Jordan Rose0e5badd2012-12-05 18:44:49 +00008296 }
Jordan Roseaee34382012-09-05 22:56:26 +00008297 }
Jordan Rose22b74712012-09-05 22:56:19 +00008298 } else {
8299 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8300 SpecifierLen);
8301 // Since the warning for passing non-POD types to variadic functions
8302 // was deferred until now, we emit a warning for non-POD
8303 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00008304 switch (S.isValidVarArgType(ExprTy)) {
8305 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00008306 case Sema::VAK_ValidInCXX11: {
JF Bastienec7d7f32018-06-22 21:54:40 +00008307 unsigned Diag =
8308 Pedantic
8309 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8310 : diag::warn_format_conversion_argument_type_mismatch;
Richard Smithd7293d72013-08-05 18:49:43 +00008311
Seth Cantrellb4802962015-03-04 03:12:10 +00008312 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008313 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
Seth Cantrellb4802962015-03-04 03:12:10 +00008314 << IsEnum << CSR << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008315 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Seth Cantrellb4802962015-03-04 03:12:10 +00008316 break;
8317 }
Richard Smithd7293d72013-08-05 18:49:43 +00008318 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00008319 case Sema::VAK_MSVCUndefined:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008320 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8321 << S.getLangOpts().CPlusPlus11 << ExprTy
8322 << CallType
8323 << AT.getRepresentativeTypeName(S.Context) << CSR
8324 << E->getSourceRange(),
8325 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00008326 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00008327 break;
8328
8329 case Sema::VAK_Invalid:
8330 if (ExprTy->isObjCObjectType())
8331 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008332 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8333 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8334 << AT.getRepresentativeTypeName(S.Context) << CSR
8335 << E->getSourceRange(),
8336 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00008337 else
8338 // FIXME: If this is an initializer list, suggest removing the braces
8339 // or inserting a cast to the target type.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008340 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8341 << isa<InitListExpr>(E) << ExprTy << CallType
8342 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
Richard Smithd7293d72013-08-05 18:49:43 +00008343 break;
8344 }
8345
8346 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8347 "format string specifier index out of range");
8348 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008349 }
8350
Ted Kremenekab278de2010-01-28 23:39:18 +00008351 return true;
8352}
8353
Ted Kremenek02087932010-07-16 02:11:22 +00008354//===--- CHECK: Scanf format string checking ------------------------------===//
8355
Fangrui Song6907ce22018-07-30 19:24:48 +00008356namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008357
Ted Kremenek02087932010-07-16 02:11:22 +00008358class CheckScanfHandler : public CheckFormatHandler {
8359public:
Stephen Hines648c3692016-09-16 01:07:04 +00008360 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00008361 const Expr *origFormatExpr, Sema::FormatStringType type,
8362 unsigned firstDataArg, unsigned numDataArgs,
8363 const char *beg, bool hasVAListArg,
8364 ArrayRef<const Expr *> Args, unsigned formatIdx,
8365 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008366 llvm::SmallBitVector &CheckedVarArgs,
8367 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00008368 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8369 numDataArgs, beg, hasVAListArg, Args, formatIdx,
8370 inFunctionCall, CallType, CheckedVarArgs,
8371 UncoveredArg) {}
8372
Ted Kremenek02087932010-07-16 02:11:22 +00008373 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8374 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00008375 unsigned specifierLen) override;
Fangrui Song6907ce22018-07-30 19:24:48 +00008376
Ted Kremenekce815422010-07-19 21:25:57 +00008377 bool HandleInvalidScanfConversionSpecifier(
8378 const analyze_scanf::ScanfSpecifier &FS,
8379 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00008380 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008381
Craig Toppere14c0f82014-03-12 04:55:44 +00008382 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00008383};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008384
8385} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00008386
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008387void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8388 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008389 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8390 getLocationOfByte(end), /*IsStringLocation*/true,
8391 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008392}
8393
Ted Kremenekce815422010-07-19 21:25:57 +00008394bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8395 const analyze_scanf::ScanfSpecifier &FS,
8396 const char *startSpecifier,
8397 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008398 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00008399 FS.getConversionSpecifier();
8400
8401 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8402 getLocationOfByte(CS.getStart()),
8403 startSpecifier, specifierLen,
8404 CS.getStart(), CS.getLength());
8405}
8406
Ted Kremenek02087932010-07-16 02:11:22 +00008407bool CheckScanfHandler::HandleScanfSpecifier(
8408 const analyze_scanf::ScanfSpecifier &FS,
8409 const char *startSpecifier,
8410 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00008411 using namespace analyze_scanf;
Fangrui Song6907ce22018-07-30 19:24:48 +00008412 using namespace analyze_format_string;
Ted Kremenek02087932010-07-16 02:11:22 +00008413
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008414 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00008415
Ted Kremenek6cd69422010-07-19 22:01:06 +00008416 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8417 // be used to decide if we are using positional arguments consistently.
8418 if (FS.consumesDataArgument()) {
8419 if (atFirstArg) {
8420 atFirstArg = false;
8421 usesPositionalArgs = FS.usesPositionalArg();
8422 }
8423 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008424 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8425 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00008426 return false;
8427 }
Ted Kremenek02087932010-07-16 02:11:22 +00008428 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008429
Ted Kremenek02087932010-07-16 02:11:22 +00008430 // Check if the field with is non-zero.
8431 const OptionalAmount &Amt = FS.getFieldWidth();
8432 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8433 if (Amt.getConstantAmount() == 0) {
8434 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8435 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00008436 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8437 getLocationOfByte(Amt.getStart()),
8438 /*IsStringLocation*/true, R,
8439 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00008440 }
8441 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008442
Ted Kremenek02087932010-07-16 02:11:22 +00008443 if (!FS.consumesDataArgument()) {
8444 // FIXME: Technically specifying a precision or field width here
8445 // makes no sense. Worth issuing a warning at some point.
8446 return true;
8447 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008448
Ted Kremenek02087932010-07-16 02:11:22 +00008449 // Consume the argument.
8450 unsigned argIndex = FS.getArgIndex();
8451 if (argIndex < NumDataArgs) {
8452 // The check to see if the argIndex is valid will come later.
8453 // We set the bit here because we may exit early from this
8454 // function if we encounter some other error.
8455 CoveredArgs.set(argIndex);
8456 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008457
Ted Kremenek4407ea42010-07-20 20:04:47 +00008458 // Check the length modifier is valid with the given conversion specifier.
Matt Arsenault58fc8082019-01-29 20:49:54 +00008459 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8460 S.getLangOpts()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00008461 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8462 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00008463 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008464 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00008465 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008466 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8467 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00008468
Jordan Rose92303592012-09-08 04:00:03 +00008469 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8470 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8471
Ted Kremenek02087932010-07-16 02:11:22 +00008472 // The remaining checks depend on the data arguments.
8473 if (HasVAListArg)
8474 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008475
Ted Kremenek6adb7e32010-07-26 19:45:42 +00008476 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00008477 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00008478
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008479 // Check that the argument type matches the format specifier.
8480 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00008481 if (!Ex)
8482 return true;
8483
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00008484 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00008485
8486 if (!AT.isValid()) {
8487 return true;
8488 }
8489
JF Bastienec7d7f32018-06-22 21:54:40 +00008490 analyze_format_string::ArgType::MatchKind Match =
Seth Cantrellb4802962015-03-04 03:12:10 +00008491 AT.matchesType(S.Context, Ex->getType());
JF Bastienec7d7f32018-06-22 21:54:40 +00008492 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8493 if (Match == analyze_format_string::ArgType::Match)
Seth Cantrell79340072015-03-04 05:58:08 +00008494 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008495
Seth Cantrell79340072015-03-04 05:58:08 +00008496 ScanfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00008497 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
Seth Cantrell79340072015-03-04 05:58:08 +00008498 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008499
JF Bastienec7d7f32018-06-22 21:54:40 +00008500 unsigned Diag =
8501 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8502 : diag::warn_format_conversion_argument_type_mismatch;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008503
JF Bastienec7d7f32018-06-22 21:54:40 +00008504 if (Success) {
Seth Cantrell79340072015-03-04 05:58:08 +00008505 // Get the fix string from the fixed format specifier.
8506 SmallString<128> buf;
8507 llvm::raw_svector_ostream os(buf);
8508 fixedFS.toString(os);
8509
8510 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008511 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
Seth Cantrell79340072015-03-04 05:58:08 +00008512 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008513 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008514 /*IsStringLocation*/ false,
8515 getSpecifierRange(startSpecifier, specifierLen),
8516 FixItHint::CreateReplacement(
8517 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8518 } else {
JF Bastienec7d7f32018-06-22 21:54:40 +00008519 EmitFormatDiagnostic(S.PDiag(Diag)
Seth Cantrell79340072015-03-04 05:58:08 +00008520 << AT.getRepresentativeTypeName(S.Context)
8521 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008522 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008523 /*IsStringLocation*/ false,
8524 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008525 }
8526
Ted Kremenek02087932010-07-16 02:11:22 +00008527 return true;
8528}
8529
Stephen Hines648c3692016-09-16 01:07:04 +00008530static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008531 const Expr *OrigFormatExpr,
8532 ArrayRef<const Expr *> Args,
8533 bool HasVAListArg, unsigned format_idx,
8534 unsigned firstDataArg,
8535 Sema::FormatStringType Type,
8536 bool inFunctionCall,
8537 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008538 llvm::SmallBitVector &CheckedVarArgs,
Erik Pilkingtonaa385562019-08-14 16:57:11 +00008539 UncoveredArgHandler &UncoveredArg,
8540 bool IgnoreStringsWithoutSpecifiers) {
Ted Kremenekab278de2010-01-28 23:39:18 +00008541 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00008542 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008543 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008544 S, inFunctionCall, Args[format_idx],
8545 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8546 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008547 return;
8548 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008549
Ted Kremenekab278de2010-01-28 23:39:18 +00008550 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008551 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00008552 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008553 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008554 const ConstantArrayType *T =
8555 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008556 assert(T && "String literal not of constant array type!");
8557 size_t TypeSize = T->getSize().getZExtValue();
8558 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00008559 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008560
Erik Pilkingtonaa385562019-08-14 16:57:11 +00008561 if (IgnoreStringsWithoutSpecifiers &&
8562 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8563 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8564 return;
8565
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008566 // Emit a warning if the string literal is truncated and does not contain an
8567 // embedded null character.
8568 if (TypeSize <= StrRef.size() &&
8569 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8570 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008571 S, inFunctionCall, Args[format_idx],
8572 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008573 FExpr->getBeginLoc(),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008574 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8575 return;
8576 }
8577
Ted Kremenekab278de2010-01-28 23:39:18 +00008578 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00008579 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008580 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008581 S, inFunctionCall, Args[format_idx],
8582 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8583 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008584 return;
8585 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008586
8587 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00008588 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8589 Type == Sema::FST_OSTrace) {
8590 CheckPrintfHandler H(
8591 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8592 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8593 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8594 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008595
Hans Wennborg23926bd2011-12-15 10:25:47 +00008596 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008597 S.getLangOpts(),
8598 S.Context.getTargetInfo(),
8599 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00008600 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008601 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00008602 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8603 numDataArgs, Str, HasVAListArg, Args, format_idx,
8604 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008605
Hans Wennborg23926bd2011-12-15 10:25:47 +00008606 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008607 S.getLangOpts(),
8608 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00008609 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00008610 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00008611}
8612
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00008613bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8614 // Str - The format string. NOTE: this is NOT null-terminated!
8615 StringRef StrRef = FExpr->getString();
8616 const char *Str = StrRef.data();
8617 // Account for cases where the string literal is truncated in a declaration.
8618 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8619 assert(T && "String literal not of constant array type!");
8620 size_t TypeSize = T->getSize().getZExtValue();
8621 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8622 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8623 getLangOpts(),
8624 Context.getTargetInfo());
8625}
8626
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008627//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8628
8629// Returns the related absolute value function that is larger, of 0 if one
8630// does not exist.
8631static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8632 switch (AbsFunction) {
8633 default:
8634 return 0;
8635
8636 case Builtin::BI__builtin_abs:
8637 return Builtin::BI__builtin_labs;
8638 case Builtin::BI__builtin_labs:
8639 return Builtin::BI__builtin_llabs;
8640 case Builtin::BI__builtin_llabs:
8641 return 0;
8642
8643 case Builtin::BI__builtin_fabsf:
8644 return Builtin::BI__builtin_fabs;
8645 case Builtin::BI__builtin_fabs:
8646 return Builtin::BI__builtin_fabsl;
8647 case Builtin::BI__builtin_fabsl:
8648 return 0;
8649
8650 case Builtin::BI__builtin_cabsf:
8651 return Builtin::BI__builtin_cabs;
8652 case Builtin::BI__builtin_cabs:
8653 return Builtin::BI__builtin_cabsl;
8654 case Builtin::BI__builtin_cabsl:
8655 return 0;
8656
8657 case Builtin::BIabs:
8658 return Builtin::BIlabs;
8659 case Builtin::BIlabs:
8660 return Builtin::BIllabs;
8661 case Builtin::BIllabs:
8662 return 0;
8663
8664 case Builtin::BIfabsf:
8665 return Builtin::BIfabs;
8666 case Builtin::BIfabs:
8667 return Builtin::BIfabsl;
8668 case Builtin::BIfabsl:
8669 return 0;
8670
8671 case Builtin::BIcabsf:
8672 return Builtin::BIcabs;
8673 case Builtin::BIcabs:
8674 return Builtin::BIcabsl;
8675 case Builtin::BIcabsl:
8676 return 0;
8677 }
8678}
8679
8680// Returns the argument type of the absolute value function.
8681static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8682 unsigned AbsType) {
8683 if (AbsType == 0)
8684 return QualType();
8685
8686 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8687 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8688 if (Error != ASTContext::GE_None)
8689 return QualType();
8690
8691 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8692 if (!FT)
8693 return QualType();
8694
8695 if (FT->getNumParams() != 1)
8696 return QualType();
8697
8698 return FT->getParamType(0);
8699}
8700
8701// Returns the best absolute value function, or zero, based on type and
8702// current absolute value function.
8703static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8704 unsigned AbsFunctionKind) {
8705 unsigned BestKind = 0;
8706 uint64_t ArgSize = Context.getTypeSize(ArgType);
8707 for (unsigned Kind = AbsFunctionKind; Kind != 0;
8708 Kind = getLargerAbsoluteValueFunction(Kind)) {
8709 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8710 if (Context.getTypeSize(ParamType) >= ArgSize) {
8711 if (BestKind == 0)
8712 BestKind = Kind;
8713 else if (Context.hasSameType(ParamType, ArgType)) {
8714 BestKind = Kind;
8715 break;
8716 }
8717 }
8718 }
8719 return BestKind;
8720}
8721
8722enum AbsoluteValueKind {
8723 AVK_Integer,
8724 AVK_Floating,
8725 AVK_Complex
8726};
8727
8728static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8729 if (T->isIntegralOrEnumerationType())
8730 return AVK_Integer;
8731 if (T->isRealFloatingType())
8732 return AVK_Floating;
8733 if (T->isAnyComplexType())
8734 return AVK_Complex;
8735
8736 llvm_unreachable("Type not integer, floating, or complex");
8737}
8738
8739// Changes the absolute value function to a different type. Preserves whether
8740// the function is a builtin.
8741static unsigned changeAbsFunction(unsigned AbsKind,
8742 AbsoluteValueKind ValueKind) {
8743 switch (ValueKind) {
8744 case AVK_Integer:
8745 switch (AbsKind) {
8746 default:
8747 return 0;
8748 case Builtin::BI__builtin_fabsf:
8749 case Builtin::BI__builtin_fabs:
8750 case Builtin::BI__builtin_fabsl:
8751 case Builtin::BI__builtin_cabsf:
8752 case Builtin::BI__builtin_cabs:
8753 case Builtin::BI__builtin_cabsl:
8754 return Builtin::BI__builtin_abs;
8755 case Builtin::BIfabsf:
8756 case Builtin::BIfabs:
8757 case Builtin::BIfabsl:
8758 case Builtin::BIcabsf:
8759 case Builtin::BIcabs:
8760 case Builtin::BIcabsl:
8761 return Builtin::BIabs;
8762 }
8763 case AVK_Floating:
8764 switch (AbsKind) {
8765 default:
8766 return 0;
8767 case Builtin::BI__builtin_abs:
8768 case Builtin::BI__builtin_labs:
8769 case Builtin::BI__builtin_llabs:
8770 case Builtin::BI__builtin_cabsf:
8771 case Builtin::BI__builtin_cabs:
8772 case Builtin::BI__builtin_cabsl:
8773 return Builtin::BI__builtin_fabsf;
8774 case Builtin::BIabs:
8775 case Builtin::BIlabs:
8776 case Builtin::BIllabs:
8777 case Builtin::BIcabsf:
8778 case Builtin::BIcabs:
8779 case Builtin::BIcabsl:
8780 return Builtin::BIfabsf;
8781 }
8782 case AVK_Complex:
8783 switch (AbsKind) {
8784 default:
8785 return 0;
8786 case Builtin::BI__builtin_abs:
8787 case Builtin::BI__builtin_labs:
8788 case Builtin::BI__builtin_llabs:
8789 case Builtin::BI__builtin_fabsf:
8790 case Builtin::BI__builtin_fabs:
8791 case Builtin::BI__builtin_fabsl:
8792 return Builtin::BI__builtin_cabsf;
8793 case Builtin::BIabs:
8794 case Builtin::BIlabs:
8795 case Builtin::BIllabs:
8796 case Builtin::BIfabsf:
8797 case Builtin::BIfabs:
8798 case Builtin::BIfabsl:
8799 return Builtin::BIcabsf;
8800 }
8801 }
8802 llvm_unreachable("Unable to convert function");
8803}
8804
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00008805static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008806 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8807 if (!FnInfo)
8808 return 0;
8809
8810 switch (FDecl->getBuiltinID()) {
8811 default:
8812 return 0;
8813 case Builtin::BI__builtin_abs:
8814 case Builtin::BI__builtin_fabs:
8815 case Builtin::BI__builtin_fabsf:
8816 case Builtin::BI__builtin_fabsl:
8817 case Builtin::BI__builtin_labs:
8818 case Builtin::BI__builtin_llabs:
8819 case Builtin::BI__builtin_cabs:
8820 case Builtin::BI__builtin_cabsf:
8821 case Builtin::BI__builtin_cabsl:
8822 case Builtin::BIabs:
8823 case Builtin::BIlabs:
8824 case Builtin::BIllabs:
8825 case Builtin::BIfabs:
8826 case Builtin::BIfabsf:
8827 case Builtin::BIfabsl:
8828 case Builtin::BIcabs:
8829 case Builtin::BIcabsf:
8830 case Builtin::BIcabsl:
8831 return FDecl->getBuiltinID();
8832 }
8833 llvm_unreachable("Unknown Builtin type");
8834}
8835
8836// If the replacement is valid, emit a note with replacement function.
8837// Additionally, suggest including the proper header if not already included.
8838static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00008839 unsigned AbsKind, QualType ArgType) {
8840 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00008841 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00008842 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008843 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8844 FunctionName = "std::abs";
8845 if (ArgType->isIntegralOrEnumerationType()) {
8846 HeaderName = "cstdlib";
8847 } else if (ArgType->isRealFloatingType()) {
8848 HeaderName = "cmath";
8849 } else {
8850 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008851 }
Richard Trieubeffb832014-04-15 23:47:53 +00008852
8853 // Lookup all std::abs
8854 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00008855 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00008856 R.suppressDiagnostics();
8857 S.LookupQualifiedName(R, Std);
8858
8859 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008860 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008861 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8862 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8863 } else {
8864 FDecl = dyn_cast<FunctionDecl>(I);
8865 }
8866 if (!FDecl)
8867 continue;
8868
8869 // Found std::abs(), check that they are the right ones.
8870 if (FDecl->getNumParams() != 1)
8871 continue;
8872
8873 // Check that the parameter type can handle the argument.
8874 QualType ParamType = FDecl->getParamDecl(0)->getType();
8875 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8876 S.Context.getTypeSize(ArgType) <=
8877 S.Context.getTypeSize(ParamType)) {
8878 // Found a function, don't need the header hint.
8879 EmitHeaderHint = false;
8880 break;
8881 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008882 }
Richard Trieubeffb832014-04-15 23:47:53 +00008883 }
8884 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00008885 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00008886 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8887
8888 if (HeaderName) {
8889 DeclarationName DN(&S.Context.Idents.get(FunctionName));
8890 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8891 R.suppressDiagnostics();
8892 S.LookupName(R, S.getCurScope());
8893
8894 if (R.isSingleResult()) {
8895 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8896 if (FD && FD->getBuiltinID() == AbsKind) {
8897 EmitHeaderHint = false;
8898 } else {
8899 return;
8900 }
8901 } else if (!R.empty()) {
8902 return;
8903 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008904 }
8905 }
8906
8907 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00008908 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008909
Richard Trieubeffb832014-04-15 23:47:53 +00008910 if (!HeaderName)
8911 return;
8912
8913 if (!EmitHeaderHint)
8914 return;
8915
Alp Toker5d96e0a2014-07-11 20:53:51 +00008916 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8917 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00008918}
8919
Richard Trieua7f30b12016-12-06 01:42:28 +00008920template <std::size_t StrLen>
8921static bool IsStdFunction(const FunctionDecl *FDecl,
8922 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00008923 if (!FDecl)
8924 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008925 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00008926 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008927 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00008928 return false;
8929
8930 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008931}
8932
8933// Warn when using the wrong abs() function.
8934void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00008935 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008936 if (Call->getNumArgs() != 1)
8937 return;
8938
8939 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00008940 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00008941 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008942 return;
8943
8944 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8945 QualType ParamType = Call->getArg(0)->getType();
8946
Alp Toker5d96e0a2014-07-11 20:53:51 +00008947 // Unsigned types cannot be negative. Suggest removing the absolute value
8948 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008949 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00008950 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00008951 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008952 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8953 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00008954 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008955 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8956 return;
8957 }
8958
David Majnemer7f77eb92015-11-15 03:04:34 +00008959 // Taking the absolute value of a pointer is very suspicious, they probably
8960 // wanted to index into an array, dereference a pointer, call a function, etc.
8961 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8962 unsigned DiagType = 0;
8963 if (ArgType->isFunctionType())
8964 DiagType = 1;
8965 else if (ArgType->isArrayType())
8966 DiagType = 2;
8967
8968 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8969 return;
8970 }
8971
Richard Trieubeffb832014-04-15 23:47:53 +00008972 // std::abs has overloads which prevent most of the absolute value problems
8973 // from occurring.
8974 if (IsStdAbs)
8975 return;
8976
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008977 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8978 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8979
8980 // The argument and parameter are the same kind. Check if they are the right
8981 // size.
8982 if (ArgValueKind == ParamValueKind) {
8983 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8984 return;
8985
8986 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8987 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8988 << FDecl << ArgType << ParamType;
8989
8990 if (NewAbsKind == 0)
8991 return;
8992
8993 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00008994 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008995 return;
8996 }
8997
8998 // ArgValueKind != ParamValueKind
8999 // The wrong type of absolute value function was used. Attempt to find the
9000 // proper one.
9001 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9002 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9003 if (NewAbsKind == 0)
9004 return;
9005
9006 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9007 << FDecl << ParamValueKind << ArgValueKind;
9008
9009 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00009010 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009011}
9012
Richard Trieu67c00712016-12-05 23:41:46 +00009013//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00009014void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9015 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00009016 if (!Call || !FDecl) return;
9017
9018 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00009019 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00009020 if (Call->getExprLoc().isMacroID()) return;
9021
9022 // Only care about the one template argument, two function parameter std::max
9023 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00009024 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00009025 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9026 if (!ArgList) return;
9027 if (ArgList->size() != 1) return;
9028
9029 // Check that template type argument is unsigned integer.
9030 const auto& TA = ArgList->get(0);
9031 if (TA.getKind() != TemplateArgument::Type) return;
9032 QualType ArgType = TA.getAsType();
9033 if (!ArgType->isUnsignedIntegerType()) return;
9034
9035 // See if either argument is a literal zero.
9036 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9037 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9038 if (!MTE) return false;
9039 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
9040 if (!Num) return false;
9041 if (Num->getValue() != 0) return false;
9042 return true;
9043 };
9044
9045 const Expr *FirstArg = Call->getArg(0);
9046 const Expr *SecondArg = Call->getArg(1);
9047 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9048 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9049
9050 // Only warn when exactly one argument is zero.
9051 if (IsFirstArgZero == IsSecondArgZero) return;
9052
9053 SourceRange FirstRange = FirstArg->getSourceRange();
9054 SourceRange SecondRange = SecondArg->getSourceRange();
9055
9056 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9057
9058 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9059 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9060
9061 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9062 SourceRange RemovalRange;
9063 if (IsFirstArgZero) {
9064 RemovalRange = SourceRange(FirstRange.getBegin(),
9065 SecondRange.getBegin().getLocWithOffset(-1));
9066 } else {
9067 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9068 SecondRange.getEnd());
9069 }
9070
9071 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9072 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9073 << FixItHint::CreateRemoval(RemovalRange);
9074}
9075
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009076//===--- CHECK: Standard memory functions ---------------------------------===//
9077
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009078/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00009079/// such as memcmp, strncat, etc and warns if it's a comparison.
9080///
9081/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9082static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9083 IdentifierInfo *FnName,
9084 SourceLocation FnLoc,
9085 SourceLocation RParenLoc) {
9086 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9087 if (!Size)
9088 return false;
9089
Richard Smithc70f1d62017-12-14 15:16:18 +00009090 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9091 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00009092 return false;
9093
Nico Weber0e6daef2013-12-26 23:38:39 +00009094 SourceRange SizeRange = Size->getSourceRange();
9095 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9096 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00009097 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009098 << FnName
9099 << FixItHint::CreateInsertion(
9100 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00009101 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00009102 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00009103 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00009104 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9105 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00009106
9107 return true;
9108}
9109
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009110/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00009111/// (e.g., whether it has a vtable).
9112static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9113 bool &IsContained) {
9114 // Look through array types while ignoring qualifiers.
9115 const Type *Ty = T->getBaseElementTypeUnsafe();
9116 IsContained = false;
9117
9118 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9119 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00009120 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00009121 return nullptr;
9122
9123 if (RD->isDynamicClass())
9124 return RD;
9125
9126 // Check all the fields. If any bases were dynamic, the class is dynamic.
9127 // It's impossible for a class to transitively contain itself by value, so
9128 // infinite recursion is impossible.
9129 for (auto *FD : RD->fields()) {
9130 bool SubContained;
9131 if (const CXXRecordDecl *ContainedRD =
9132 getContainedDynamicClass(FD->getType(), SubContained)) {
9133 IsContained = true;
9134 return ContainedRD;
9135 }
9136 }
9137
9138 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00009139}
9140
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009141static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9142 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9143 if (Unary->getKind() == UETT_SizeOf)
9144 return Unary;
9145 return nullptr;
9146}
9147
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009148/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009149/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00009150static const Expr *getSizeOfExprArg(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009151 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9152 if (!SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009153 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Craig Topperc3ec1492014-05-26 06:22:03 +00009154 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009155}
9156
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009157/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00009158static QualType getSizeOfArgType(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009159 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9160 return SizeOf->getTypeOfArgument();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009161 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00009162}
9163
Akira Hatanaka2be04412018-04-17 19:13:41 +00009164namespace {
9165
9166struct SearchNonTrivialToInitializeField
9167 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9168 using Super =
9169 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9170
9171 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9172
9173 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9174 SourceLocation SL) {
9175 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9176 asDerived().visitArray(PDIK, AT, SL);
9177 return;
9178 }
9179
9180 Super::visitWithKind(PDIK, FT, SL);
9181 }
9182
9183 void visitARCStrong(QualType FT, SourceLocation SL) {
9184 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9185 }
9186 void visitARCWeak(QualType FT, SourceLocation SL) {
9187 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9188 }
9189 void visitStruct(QualType FT, SourceLocation SL) {
9190 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9191 visit(FD->getType(), FD->getLocation());
9192 }
9193 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9194 const ArrayType *AT, SourceLocation SL) {
9195 visit(getContext().getBaseElementType(AT), SL);
9196 }
9197 void visitTrivial(QualType FT, SourceLocation SL) {}
9198
9199 static void diag(QualType RT, const Expr *E, Sema &S) {
9200 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9201 }
9202
9203 ASTContext &getContext() { return S.getASTContext(); }
9204
9205 const Expr *E;
9206 Sema &S;
9207};
9208
9209struct SearchNonTrivialToCopyField
9210 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9211 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9212
9213 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9214
9215 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9216 SourceLocation SL) {
9217 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9218 asDerived().visitArray(PCK, AT, SL);
9219 return;
9220 }
9221
9222 Super::visitWithKind(PCK, FT, SL);
9223 }
9224
9225 void visitARCStrong(QualType FT, SourceLocation SL) {
9226 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9227 }
9228 void visitARCWeak(QualType FT, SourceLocation SL) {
9229 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9230 }
9231 void visitStruct(QualType FT, SourceLocation SL) {
9232 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9233 visit(FD->getType(), FD->getLocation());
9234 }
9235 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9236 SourceLocation SL) {
9237 visit(getContext().getBaseElementType(AT), SL);
9238 }
9239 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9240 SourceLocation SL) {}
9241 void visitTrivial(QualType FT, SourceLocation SL) {}
9242 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9243
9244 static void diag(QualType RT, const Expr *E, Sema &S) {
9245 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9246 }
9247
9248 ASTContext &getContext() { return S.getASTContext(); }
9249
9250 const Expr *E;
9251 Sema &S;
9252};
9253
9254}
9255
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009256/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9257static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9258 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9259
9260 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9261 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9262 return false;
9263
9264 return doesExprLikelyComputeSize(BO->getLHS()) ||
9265 doesExprLikelyComputeSize(BO->getRHS());
9266 }
9267
9268 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9269}
9270
9271/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9272///
9273/// \code
9274/// #define MACRO 0
9275/// foo(MACRO);
9276/// foo(0);
9277/// \endcode
9278///
9279/// This should return true for the first call to foo, but not for the second
9280/// (regardless of whether foo is a macro or function).
9281static bool isArgumentExpandedFromMacro(SourceManager &SM,
9282 SourceLocation CallLoc,
9283 SourceLocation ArgLoc) {
9284 if (!CallLoc.isMacroID())
9285 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9286
9287 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9288 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9289}
9290
9291/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9292/// last two arguments transposed.
9293static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9294 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9295 return;
9296
9297 const Expr *SizeArg =
9298 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9299
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009300 auto isLiteralZero = [](const Expr *E) {
9301 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9302 };
9303
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009304 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9305 SourceLocation CallLoc = Call->getRParenLoc();
9306 SourceManager &SM = S.getSourceManager();
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009307 if (isLiteralZero(SizeArg) &&
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009308 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9309
9310 SourceLocation DiagLoc = SizeArg->getExprLoc();
9311
9312 // Some platforms #define bzero to __builtin_memset. See if this is the
9313 // case, and if so, emit a better diagnostic.
9314 if (BId == Builtin::BIbzero ||
9315 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9316 CallLoc, SM, S.getLangOpts()) == "bzero")) {
9317 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9318 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009319 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009320 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9321 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9322 }
9323 return;
9324 }
9325
9326 // If the second argument to a memset is a sizeof expression and the third
9327 // isn't, this is also likely an error. This should catch
9328 // 'memset(buf, sizeof(buf), 0xff)'.
9329 if (BId == Builtin::BImemset &&
9330 doesExprLikelyComputeSize(Call->getArg(1)) &&
9331 !doesExprLikelyComputeSize(Call->getArg(2))) {
9332 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9333 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9334 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9335 return;
9336 }
9337}
9338
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009339/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009340///
Chandler Carruthac687262011-06-03 06:23:57 +00009341/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009342/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9343/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009344///
9345/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009346void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00009347 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009348 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00009349 assert(BId != 0);
9350
Ted Kremenekb5fabb22011-04-28 01:38:02 +00009351 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00009352 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009353 unsigned ExpectedNumArgs =
9354 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00009355 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00009356 return;
9357
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009358 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00009359 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009360 unsigned LenArg =
9361 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00009362 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009363
Nico Weber0e6daef2013-12-26 23:38:39 +00009364 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009365 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009366 return;
9367
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009368 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9369 CheckMemaccessSize(*this, BId, Call);
9370
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009371 // We have special checking when the length is a sizeof expression.
9372 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9373 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9374 llvm::FoldingSetNodeID SizeOfArgID;
9375
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00009376 // Although widely used, 'bzero' is not a standard function. Be more strict
9377 // with the argument types before allowing diagnostics and only allow the
9378 // form bzero(ptr, sizeof(...)).
9379 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9380 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9381 return;
9382
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009383 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9384 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00009385 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009386
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009387 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00009388 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009389 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00009390 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00009391
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009392 // Never warn about void type pointers. This can be used to suppress
9393 // false positives.
9394 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009395 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009396
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009397 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9398 // actually comparing the expressions for equality. Because computing the
9399 // expression IDs can be expensive, we only do this if the diagnostic is
9400 // enabled.
9401 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009402 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9403 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009404 // We only compute IDs for expressions if the warning is enabled, and
9405 // cache the sizeof arg's ID.
9406 if (SizeOfArgID == llvm::FoldingSetNodeID())
9407 SizeOfArg->Profile(SizeOfArgID, Context, true);
9408 llvm::FoldingSetNodeID DestID;
9409 Dest->Profile(DestID, Context, true);
9410 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00009411 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9412 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009413 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00009414 StringRef ReadableName = FnName->getName();
9415
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009416 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00009417 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009418 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00009419 if (!PointeeTy->isIncompleteType() &&
9420 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009421 ActionIdx = 2; // If the pointee's size is sizeof(char),
9422 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00009423
9424 // If the function is defined as a builtin macro, do not show macro
9425 // expansion.
9426 SourceLocation SL = SizeOfArg->getExprLoc();
9427 SourceRange DSR = Dest->getSourceRange();
9428 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009429 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00009430
9431 if (SM.isMacroArgExpansion(SL)) {
9432 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9433 SL = SM.getSpellingLoc(SL);
9434 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9435 SM.getSpellingLoc(DSR.getEnd()));
9436 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9437 SM.getSpellingLoc(SSR.getEnd()));
9438 }
9439
Anna Zaksd08d9152012-05-30 23:14:52 +00009440 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009441 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00009442 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00009443 << PointeeTy
9444 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00009445 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00009446 << SSR);
9447 DiagRuntimeBehavior(SL, SizeOfArg,
9448 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9449 << ActionIdx
9450 << SSR);
9451
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009452 break;
9453 }
9454 }
9455
9456 // Also check for cases where the sizeof argument is the exact same
9457 // type as the memory argument, and where it points to a user-defined
9458 // record type.
9459 if (SizeOfArgTy != QualType()) {
9460 if (PointeeTy->isRecordType() &&
9461 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9462 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9463 PDiag(diag::warn_sizeof_pointer_type_memaccess)
9464 << FnName << SizeOfArgTy << ArgIdx
9465 << PointeeTy << Dest->getSourceRange()
9466 << LenExpr->getSourceRange());
9467 break;
9468 }
Nico Weberc5e73862011-06-14 16:14:58 +00009469 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00009470 } else if (DestTy->isArrayType()) {
9471 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00009472 }
Nico Weberc5e73862011-06-14 16:14:58 +00009473
Nico Weberc44b35e2015-03-21 17:37:46 +00009474 if (PointeeTy == QualType())
9475 continue;
Anna Zaks22122702012-01-17 00:37:07 +00009476
Nico Weberc44b35e2015-03-21 17:37:46 +00009477 // Always complain about dynamic classes.
9478 bool IsContained;
9479 if (const CXXRecordDecl *ContainedRD =
9480 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00009481
Nico Weberc44b35e2015-03-21 17:37:46 +00009482 unsigned OperationType = 0;
Clement Courbet8c3343d2019-02-14 12:00:34 +00009483 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
Nico Weberc44b35e2015-03-21 17:37:46 +00009484 // "overwritten" if we're warning about the destination for any call
9485 // but memcmp; otherwise a verb appropriate to the call.
Clement Courbet8c3343d2019-02-14 12:00:34 +00009486 if (ArgIdx != 0 || IsCmp) {
Nico Weberc44b35e2015-03-21 17:37:46 +00009487 if (BId == Builtin::BImemcpy)
9488 OperationType = 1;
9489 else if(BId == Builtin::BImemmove)
9490 OperationType = 2;
Clement Courbet8c3343d2019-02-14 12:00:34 +00009491 else if (IsCmp)
Nico Weberc44b35e2015-03-21 17:37:46 +00009492 OperationType = 3;
9493 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009494
Clement Courbet8c3343d2019-02-14 12:00:34 +00009495 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9496 PDiag(diag::warn_dyn_class_memaccess)
9497 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9498 << IsContained << ContainedRD << OperationType
9499 << Call->getCallee()->getSourceRange());
Nico Weberc44b35e2015-03-21 17:37:46 +00009500 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9501 BId != Builtin::BImemset)
9502 DiagRuntimeBehavior(
9503 Dest->getExprLoc(), Dest,
9504 PDiag(diag::warn_arc_object_memaccess)
9505 << ArgIdx << FnName << PointeeTy
9506 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00009507 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9508 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9509 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9510 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9511 PDiag(diag::warn_cstruct_memaccess)
9512 << ArgIdx << FnName << PointeeTy << 0);
9513 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9514 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9515 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9516 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9517 PDiag(diag::warn_cstruct_memaccess)
9518 << ArgIdx << FnName << PointeeTy << 1);
9519 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9520 } else {
9521 continue;
9522 }
9523 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00009524 continue;
9525
9526 DiagRuntimeBehavior(
9527 Dest->getExprLoc(), Dest,
9528 PDiag(diag::note_bad_memaccess_silence)
9529 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9530 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009531 }
9532}
9533
Ted Kremenek6865f772011-08-18 20:55:45 +00009534// A little helper routine: ignore addition and subtraction of integer literals.
9535// This intentionally does not ignore all integer constant expressions because
9536// we don't want to remove sizeof().
9537static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9538 Ex = Ex->IgnoreParenCasts();
9539
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009540 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00009541 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9542 if (!BO || !BO->isAdditiveOp())
9543 break;
9544
9545 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9546 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00009547
Ted Kremenek6865f772011-08-18 20:55:45 +00009548 if (isa<IntegerLiteral>(RHS))
9549 Ex = LHS;
9550 else if (isa<IntegerLiteral>(LHS))
9551 Ex = RHS;
9552 else
9553 break;
9554 }
9555
9556 return Ex;
9557}
9558
Anna Zaks13b08572012-08-08 21:42:23 +00009559static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9560 ASTContext &Context) {
9561 // Only handle constant-sized or VLAs, but not flexible members.
9562 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9563 // Only issue the FIXIT for arrays of size > 1.
9564 if (CAT->getSize().getSExtValue() <= 1)
9565 return false;
9566 } else if (!Ty->isVariableArrayType()) {
9567 return false;
9568 }
9569 return true;
9570}
9571
Ted Kremenek6865f772011-08-18 20:55:45 +00009572// Warn if the user has made the 'size' argument to strlcpy or strlcat
9573// be the size of the source, instead of the destination.
9574void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9575 IdentifierInfo *FnName) {
9576
9577 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00009578 unsigned NumArgs = Call->getNumArgs();
9579 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00009580 return;
9581
9582 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9583 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00009584 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00009585
9586 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009587 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009588 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009589
Ted Kremenek6865f772011-08-18 20:55:45 +00009590 // Look for 'strlcpy(dst, x, sizeof(x))'
9591 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9592 CompareWithSrc = Ex;
9593 else {
9594 // Look for 'strlcpy(dst, x, strlen(x))'
9595 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00009596 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9597 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00009598 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9599 }
9600 }
9601
9602 if (!CompareWithSrc)
9603 return;
9604
9605 // Determine if the argument to sizeof/strlen is equal to the source
9606 // argument. In principle there's all kinds of things you could do
9607 // here, for instance creating an == expression and evaluating it with
9608 // EvaluateAsBooleanCondition, but this uses a more direct technique:
9609 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9610 if (!SrcArgDRE)
9611 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009612
Ted Kremenek6865f772011-08-18 20:55:45 +00009613 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
Fangrui Song6907ce22018-07-30 19:24:48 +00009614 if (!CompareWithSrcDRE ||
Ted Kremenek6865f772011-08-18 20:55:45 +00009615 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9616 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009617
Ted Kremenek6865f772011-08-18 20:55:45 +00009618 const Expr *OriginalSizeArg = Call->getArg(2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009619 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9620 << OriginalSizeArg->getSourceRange() << FnName;
Fangrui Song6907ce22018-07-30 19:24:48 +00009621
Ted Kremenek6865f772011-08-18 20:55:45 +00009622 // Output a FIXIT hint if the destination is an array (rather than a
9623 // pointer to an array). This could be enhanced to handle some
9624 // pointers if we know the actual size, like if DstArg is 'array+2'
9625 // we could say 'sizeof(array)-2'.
9626 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00009627 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00009628 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009629
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009630 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009631 llvm::raw_svector_ostream OS(sizeString);
9632 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009633 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00009634 OS << ")";
Fangrui Song6907ce22018-07-30 19:24:48 +00009635
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009636 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9637 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9638 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00009639}
9640
Anna Zaks314cd092012-02-01 19:08:57 +00009641/// Check if two expressions refer to the same declaration.
9642static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9643 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9644 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9645 return D1->getDecl() == D2->getDecl();
9646 return false;
9647}
9648
9649static const Expr *getStrlenExprArg(const Expr *E) {
9650 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9651 const FunctionDecl *FD = CE->getDirectCallee();
9652 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00009653 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009654 return CE->getArg(0)->IgnoreParenCasts();
9655 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009656 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009657}
9658
9659// Warn on anti-patterns as the 'size' argument to strncat.
9660// The correct size argument should look like following:
9661// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9662void Sema::CheckStrncatArguments(const CallExpr *CE,
9663 IdentifierInfo *FnName) {
9664 // Don't crash if the user has the wrong number of arguments.
9665 if (CE->getNumArgs() < 3)
9666 return;
9667 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9668 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9669 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9670
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009671 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
Nico Weber0e6daef2013-12-26 23:38:39 +00009672 CE->getRParenLoc()))
9673 return;
9674
Anna Zaks314cd092012-02-01 19:08:57 +00009675 // Identify common expressions, which are wrongly used as the size argument
9676 // to strncat and may lead to buffer overflows.
9677 unsigned PatternType = 0;
9678 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9679 // - sizeof(dst)
9680 if (referToTheSameDecl(SizeOfArg, DstArg))
9681 PatternType = 1;
9682 // - sizeof(src)
9683 else if (referToTheSameDecl(SizeOfArg, SrcArg))
9684 PatternType = 2;
9685 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9686 if (BE->getOpcode() == BO_Sub) {
9687 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9688 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9689 // - sizeof(dst) - strlen(dst)
9690 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9691 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9692 PatternType = 1;
9693 // - sizeof(src) - (anything)
9694 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9695 PatternType = 2;
9696 }
9697 }
9698
9699 if (PatternType == 0)
9700 return;
9701
Anna Zaks5069aa32012-02-03 01:27:37 +00009702 // Generate the diagnostic.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009703 SourceLocation SL = LenArg->getBeginLoc();
Anna Zaks5069aa32012-02-03 01:27:37 +00009704 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009705 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00009706
9707 // If the function is defined as a builtin macro, do not show macro expansion.
9708 if (SM.isMacroArgExpansion(SL)) {
9709 SL = SM.getSpellingLoc(SL);
9710 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9711 SM.getSpellingLoc(SR.getEnd()));
9712 }
9713
Anna Zaks13b08572012-08-08 21:42:23 +00009714 // Check if the destination is an array (rather than a pointer to an array).
9715 QualType DstTy = DstArg->getType();
9716 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9717 Context);
9718 if (!isKnownSizeArray) {
9719 if (PatternType == 1)
9720 Diag(SL, diag::warn_strncat_wrong_size) << SR;
9721 else
9722 Diag(SL, diag::warn_strncat_src_size) << SR;
9723 return;
9724 }
9725
Anna Zaks314cd092012-02-01 19:08:57 +00009726 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00009727 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009728 else
Anna Zaks5069aa32012-02-03 01:27:37 +00009729 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009730
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009731 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00009732 llvm::raw_svector_ostream OS(sizeString);
9733 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009734 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009735 OS << ") - ";
9736 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009737 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009738 OS << ") - 1";
9739
Anna Zaks5069aa32012-02-03 01:27:37 +00009740 Diag(SL, diag::note_strncat_wrong_size)
9741 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00009742}
9743
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009744void
9745Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9746 SourceLocation ReturnLoc,
9747 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00009748 const AttrVec *Attrs,
9749 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009750 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00009751 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9752 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00009753 CheckNonNullExpr(*this, RetValExp))
9754 Diag(ReturnLoc, diag::warn_null_ret)
9755 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00009756
9757 // C++11 [basic.stc.dynamic.allocation]p4:
9758 // If an allocation function declared with a non-throwing
9759 // exception-specification fails to allocate storage, it shall return
9760 // a null pointer. Any other allocation function that fails to allocate
9761 // storage shall indicate failure only by throwing an exception [...]
9762 if (FD) {
9763 OverloadedOperatorKind Op = FD->getOverloadedOperator();
9764 if (Op == OO_New || Op == OO_Array_New) {
9765 const FunctionProtoType *Proto
9766 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00009767 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00009768 CheckNonNullExpr(*this, RetValExp))
9769 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9770 << FD << getLangOpts().CPlusPlus11;
9771 }
9772 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009773}
9774
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009775//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9776
9777/// Check for comparisons of floating point operands using != and ==.
9778/// Issue a warning if these are no self-comparisons, as they are not likely
9779/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00009780void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00009781 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9782 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009783
9784 // Special case: check for x == x (which is OK).
9785 // Do not emit warnings for such cases.
9786 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9787 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9788 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00009789 return;
Mike Stump11289f42009-09-09 15:08:12 +00009790
Ted Kremenekeda40e22007-11-29 00:59:04 +00009791 // Special case: check for comparisons against literals that can be exactly
9792 // represented by APFloat. In such cases, do not emit a warning. This
9793 // is a heuristic: often comparison against such literals are used to
9794 // detect if a value in a variable has not changed. This clearly can
9795 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00009796 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9797 if (FLL->isExact())
9798 return;
9799 } else
9800 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9801 if (FLR->isExact())
9802 return;
Mike Stump11289f42009-09-09 15:08:12 +00009803
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009804 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00009805 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009806 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009807 return;
Mike Stump11289f42009-09-09 15:08:12 +00009808
David Blaikie1f4ff152012-07-16 20:47:22 +00009809 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009810 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009811 return;
Mike Stump11289f42009-09-09 15:08:12 +00009812
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009813 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00009814 Diag(Loc, diag::warn_floatingpoint_eq)
9815 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009816}
John McCallca01b222010-01-04 23:21:16 +00009817
John McCall70aa5392010-01-06 05:24:50 +00009818//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9819//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00009820
John McCall70aa5392010-01-06 05:24:50 +00009821namespace {
John McCallca01b222010-01-04 23:21:16 +00009822
John McCall70aa5392010-01-06 05:24:50 +00009823/// Structure recording the 'active' range of an integer-valued
9824/// expression.
9825struct IntRange {
9826 /// The number of bits active in the int.
9827 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00009828
John McCall70aa5392010-01-06 05:24:50 +00009829 /// True if the int is known not to have negative values.
9830 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00009831
John McCall70aa5392010-01-06 05:24:50 +00009832 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009833 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00009834
John McCall817d4af2010-11-10 23:38:19 +00009835 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00009836 static IntRange forBoolType() {
9837 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00009838 }
9839
John McCall817d4af2010-11-10 23:38:19 +00009840 /// Returns the range of an opaque value of the given integral type.
9841 static IntRange forValueOfType(ASTContext &C, QualType T) {
9842 return forValueOfCanonicalType(C,
9843 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00009844 }
9845
John McCall817d4af2010-11-10 23:38:19 +00009846 /// Returns the range of an opaque value of a canonical integral type.
9847 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00009848 assert(T->isCanonicalUnqualified());
9849
9850 if (const VectorType *VT = dyn_cast<VectorType>(T))
9851 T = VT->getElementType().getTypePtr();
9852 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9853 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009854 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9855 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00009856
Roman Lebedevca1aaac2017-10-21 16:44:03 +00009857 if (!C.getLangOpts().CPlusPlus) {
9858 // For enum types in C code, use the underlying datatype.
9859 if (const EnumType *ET = dyn_cast<EnumType>(T))
9860 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9861 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9862 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00009863 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00009864 // In C++11, enums can have a fixed underlying type. Use this type to
9865 // compute the range.
9866 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00009867 return IntRange(C.getIntWidth(QualType(T, 0)),
9868 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00009869 }
John McCall18a2c2c2010-11-09 22:22:12 +00009870
David Majnemer6a426652013-06-07 22:07:20 +00009871 unsigned NumPositive = Enum->getNumPositiveBits();
9872 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00009873
David Majnemer6a426652013-06-07 22:07:20 +00009874 if (NumNegative == 0)
9875 return IntRange(NumPositive, true/*NonNegative*/);
9876 else
9877 return IntRange(std::max(NumPositive + 1, NumNegative),
9878 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00009879 }
John McCall70aa5392010-01-06 05:24:50 +00009880
9881 const BuiltinType *BT = cast<BuiltinType>(T);
9882 assert(BT->isInteger());
9883
9884 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9885 }
9886
John McCall817d4af2010-11-10 23:38:19 +00009887 /// Returns the "target" range of a canonical integral type, i.e.
9888 /// the range of values expressible in the type.
9889 ///
9890 /// This matches forValueOfCanonicalType except that enums have the
9891 /// full range of their type, not the range of their enumerators.
9892 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9893 assert(T->isCanonicalUnqualified());
9894
9895 if (const VectorType *VT = dyn_cast<VectorType>(T))
9896 T = VT->getElementType().getTypePtr();
9897 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9898 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009899 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9900 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009901 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00009902 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009903
9904 const BuiltinType *BT = cast<BuiltinType>(T);
9905 assert(BT->isInteger());
9906
9907 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9908 }
9909
9910 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00009911 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00009912 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00009913 L.NonNegative && R.NonNegative);
9914 }
9915
John McCall817d4af2010-11-10 23:38:19 +00009916 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00009917 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00009918 return IntRange(std::min(L.Width, R.Width),
9919 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00009920 }
9921};
9922
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009923} // namespace
9924
9925static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9926 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009927 if (value.isSigned() && value.isNegative())
9928 return IntRange(value.getMinSignedBits(), false);
9929
9930 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00009931 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009932
9933 // isNonNegative() just checks the sign bit without considering
9934 // signedness.
9935 return IntRange(value.getActiveBits(), true);
9936}
9937
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009938static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9939 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009940 if (result.isInt())
9941 return GetValueRange(C, result.getInt(), MaxWidth);
9942
9943 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00009944 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9945 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9946 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9947 R = IntRange::join(R, El);
9948 }
John McCall70aa5392010-01-06 05:24:50 +00009949 return R;
9950 }
9951
9952 if (result.isComplexInt()) {
9953 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9954 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9955 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00009956 }
9957
9958 // This can happen with lossless casts to intptr_t of "based" lvalues.
9959 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00009960 // FIXME: The only reason we need to pass the type in here is to get
9961 // the sign right on this one case. It would be nice if APValue
9962 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009963 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00009964 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00009965}
John McCall70aa5392010-01-06 05:24:50 +00009966
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009967static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009968 QualType Ty = E->getType();
9969 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9970 Ty = AtomicRHS->getValueType();
9971 return Ty;
9972}
9973
John McCall70aa5392010-01-06 05:24:50 +00009974/// Pseudo-evaluate the given integer expression, estimating the
9975/// range of values it might take.
9976///
9977/// \param MaxWidth - the width to which the value will be truncated
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00009978static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
9979 bool InConstantContext) {
John McCall70aa5392010-01-06 05:24:50 +00009980 E = E->IgnoreParens();
9981
9982 // Try a full evaluation first.
9983 Expr::EvalResult result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00009984 if (E->EvaluateAsRValue(result, C, InConstantContext))
Eli Friedmane6d33952013-07-08 20:20:06 +00009985 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009986
9987 // I think we only want to look through implicit casts here; if the
9988 // user has an explicit widening cast, we should treat the value as
9989 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009990 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00009991 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00009992 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +00009993
Eli Friedmane6d33952013-07-08 20:20:06 +00009994 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00009995
George Burgess IVdf1ed002016-01-13 01:52:39 +00009996 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9997 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00009998
John McCall70aa5392010-01-06 05:24:50 +00009999 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +000010000 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +000010001 return OutputTypeRange;
10002
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010003 IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10004 std::min(MaxWidth, OutputTypeRange.Width),
10005 InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010006
10007 // Bail out if the subexpr's range is as wide as the cast type.
10008 if (SubRange.Width >= OutputTypeRange.Width)
10009 return OutputTypeRange;
10010
10011 // Otherwise, we take the smaller width, and we're non-negative if
10012 // either the output type or the subexpr is.
10013 return IntRange(SubRange.Width,
10014 SubRange.NonNegative || OutputTypeRange.NonNegative);
10015 }
10016
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010017 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +000010018 // If we can fold the condition, just take that operand.
10019 bool CondResult;
10020 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010021 return GetExprRange(C,
10022 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10023 MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010024
10025 // Otherwise, conservatively merge.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010026 IntRange L =
10027 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10028 IntRange R =
10029 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010030 return IntRange::join(L, R);
10031 }
10032
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010033 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +000010034 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +000010035 case BO_Cmp:
10036 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +000010037
10038 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +000010039 case BO_LAnd:
10040 case BO_LOr:
10041 case BO_LT:
10042 case BO_GT:
10043 case BO_LE:
10044 case BO_GE:
10045 case BO_EQ:
10046 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +000010047 return IntRange::forBoolType();
10048
John McCallc3688382011-07-13 06:35:24 +000010049 // The type of the assignments is the type of the LHS, so the RHS
10050 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +000010051 case BO_MulAssign:
10052 case BO_DivAssign:
10053 case BO_RemAssign:
10054 case BO_AddAssign:
10055 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +000010056 case BO_XorAssign:
10057 case BO_OrAssign:
10058 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +000010059 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +000010060
John McCallc3688382011-07-13 06:35:24 +000010061 // Simple assignments just pass through the RHS, which will have
10062 // been coerced to the LHS type.
10063 case BO_Assign:
10064 // TODO: bitfields?
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010065 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
John McCallc3688382011-07-13 06:35:24 +000010066
John McCall70aa5392010-01-06 05:24:50 +000010067 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +000010068 case BO_PtrMemD:
10069 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +000010070 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010071
John McCall2ce81ad2010-01-06 22:07:33 +000010072 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +000010073 case BO_And:
10074 case BO_AndAssign:
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010075 return IntRange::meet(
10076 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10077 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
John McCall2ce81ad2010-01-06 22:07:33 +000010078
John McCall70aa5392010-01-06 05:24:50 +000010079 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +000010080 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +000010081 // ...except that we want to treat '1 << (blah)' as logically
10082 // positive. It's an important idiom.
10083 if (IntegerLiteral *I
10084 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10085 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +000010086 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +000010087 return IntRange(R.Width, /*NonNegative*/ true);
10088 }
10089 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010090 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +000010091
John McCalle3027922010-08-25 11:45:40 +000010092 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +000010093 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010094
John McCall2ce81ad2010-01-06 22:07:33 +000010095 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +000010096 case BO_Shr:
10097 case BO_ShrAssign: {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010098 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
John McCall2ce81ad2010-01-06 22:07:33 +000010099
10100 // If the shift amount is a positive constant, drop the width by
10101 // that much.
10102 llvm::APSInt shift;
10103 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10104 shift.isNonNegative()) {
10105 unsigned zext = shift.getZExtValue();
10106 if (zext >= L.Width)
10107 L.Width = (L.NonNegative ? 0 : 1);
10108 else
10109 L.Width -= zext;
10110 }
10111
10112 return L;
10113 }
10114
10115 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +000010116 case BO_Comma:
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010117 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010118
John McCall2ce81ad2010-01-06 22:07:33 +000010119 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +000010120 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +000010121 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +000010122 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +000010123 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +000010124
John McCall51431812011-07-14 22:39:48 +000010125 // The width of a division result is mostly determined by the size
10126 // of the LHS.
10127 case BO_Div: {
10128 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +000010129 unsigned opWidth = C.getIntWidth(GetExprType(E));
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010130 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
John McCall51431812011-07-14 22:39:48 +000010131
10132 // If the divisor is constant, use that.
10133 llvm::APSInt divisor;
10134 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10135 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10136 if (log2 >= L.Width)
10137 L.Width = (L.NonNegative ? 0 : 1);
10138 else
10139 L.Width = std::min(L.Width - log2, MaxWidth);
10140 return L;
10141 }
10142
10143 // Otherwise, just use the LHS's width.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010144 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
John McCall51431812011-07-14 22:39:48 +000010145 return IntRange(L.Width, L.NonNegative && R.NonNegative);
10146 }
10147
10148 // The result of a remainder can't be larger than the result of
10149 // either side.
10150 case BO_Rem: {
10151 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +000010152 unsigned opWidth = C.getIntWidth(GetExprType(E));
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010153 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10154 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
John McCall51431812011-07-14 22:39:48 +000010155
10156 IntRange meet = IntRange::meet(L, R);
10157 meet.Width = std::min(meet.Width, MaxWidth);
10158 return meet;
10159 }
10160
10161 // The default behavior is okay for these.
10162 case BO_Mul:
10163 case BO_Add:
10164 case BO_Xor:
10165 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +000010166 break;
10167 }
10168
John McCall51431812011-07-14 22:39:48 +000010169 // The default case is to treat the operation as if it were closed
10170 // on the narrowest type that encompasses both operands.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010171 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10172 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010173 return IntRange::join(L, R);
10174 }
10175
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010176 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +000010177 switch (UO->getOpcode()) {
10178 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +000010179 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +000010180 return IntRange::forBoolType();
10181
10182 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +000010183 case UO_Deref:
10184 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +000010185 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010186
10187 default:
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010188 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
John McCall70aa5392010-01-06 05:24:50 +000010189 }
10190 }
10191
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010192 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010193 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
Ted Kremeneka553fbf2013-10-14 18:55:27 +000010194
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +000010195 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +000010196 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +000010197 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +000010198
Eli Friedmane6d33952013-07-08 20:20:06 +000010199 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +000010200}
John McCall263a48b2010-01-04 23:31:57 +000010201
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010202static IntRange GetExprRange(ASTContext &C, const Expr *E,
10203 bool InConstantContext) {
10204 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010205}
10206
John McCall263a48b2010-01-04 23:31:57 +000010207/// Checks whether the given value, which currently has the given
10208/// source semantics, has the same value when coerced through the
10209/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010210static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10211 const llvm::fltSemantics &Src,
10212 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +000010213 llvm::APFloat truncated = value;
10214
10215 bool ignored;
10216 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10217 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10218
10219 return truncated.bitwiseIsEqual(value);
10220}
10221
10222/// Checks whether the given value, which currently has the given
10223/// source semantics, has the same value when coerced through the
10224/// target semantics.
10225///
10226/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010227static bool IsSameFloatAfterCast(const APValue &value,
10228 const llvm::fltSemantics &Src,
10229 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +000010230 if (value.isFloat())
10231 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10232
10233 if (value.isVector()) {
10234 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10235 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10236 return false;
10237 return true;
10238 }
10239
10240 assert(value.isComplexFloat());
10241 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10242 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10243}
10244
Ziang Wan87b668b2019-08-01 00:16:43 +000010245static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10246 bool IsListInit = false);
John McCallcc7e5bf2010-05-06 08:58:33 +000010247
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010248static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +000010249 // Suppress cases where we are comparing against an enum constant.
10250 if (const DeclRefExpr *DR =
10251 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10252 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +000010253 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +000010254
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010255 // Suppress cases where the value is expanded from a macro, unless that macro
10256 // is how a language represents a boolean literal. This is the case in both C
10257 // and Objective-C.
10258 SourceLocation BeginLoc = E->getBeginLoc();
10259 if (BeginLoc.isMacroID()) {
10260 StringRef MacroName = Lexer::getImmediateMacroName(
10261 BeginLoc, S.getSourceManager(), S.getLangOpts());
10262 return MacroName != "YES" && MacroName != "NO" &&
10263 MacroName != "true" && MacroName != "false";
10264 }
Ted Kremenek6274be42010-09-23 21:43:44 +000010265
Roman Lebedev6de129e2017-10-15 20:13:17 +000010266 return false;
10267}
10268
Richard Smith692f66ab2017-12-06 19:23:19 +000010269static bool isKnownToHaveUnsignedValue(Expr *E) {
10270 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +000010271 (!E->getType()->isSignedIntegerType() ||
10272 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10273}
10274
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010275namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +000010276/// The promoted range of values of a type. In general this has the
10277/// following structure:
10278///
10279/// |-----------| . . . |-----------|
10280/// ^ ^ ^ ^
10281/// Min HoleMin HoleMax Max
10282///
10283/// ... where there is only a hole if a signed type is promoted to unsigned
10284/// (in which case Min and Max are the smallest and largest representable
10285/// values).
10286struct PromotedRange {
10287 // Min, or HoleMax if there is a hole.
10288 llvm::APSInt PromotedMin;
10289 // Max, or HoleMin if there is a hole.
10290 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010291
Richard Smitha5370fb2017-12-08 22:57:11 +000010292 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10293 if (R.Width == 0)
10294 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10295 else if (R.Width >= BitWidth && !Unsigned) {
10296 // Promotion made the type *narrower*. This happens when promoting
10297 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10298 // Treat all values of 'signed int' as being in range for now.
10299 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10300 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10301 } else {
10302 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10303 .extOrTrunc(BitWidth);
10304 PromotedMin.setIsUnsigned(Unsigned);
10305
10306 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10307 .extOrTrunc(BitWidth);
10308 PromotedMax.setIsUnsigned(Unsigned);
10309 }
10310 }
10311
10312 // Determine whether this range is contiguous (has no hole).
10313 bool isContiguous() const { return PromotedMin <= PromotedMax; }
10314
10315 // Where a constant value is within the range.
10316 enum ComparisonResult {
10317 LT = 0x1,
10318 LE = 0x2,
10319 GT = 0x4,
10320 GE = 0x8,
10321 EQ = 0x10,
10322 NE = 0x20,
10323 InRangeFlag = 0x40,
10324
10325 Less = LE | LT | NE,
10326 Min = LE | InRangeFlag,
10327 InRange = InRangeFlag,
10328 Max = GE | InRangeFlag,
10329 Greater = GE | GT | NE,
10330
10331 OnlyValue = LE | GE | EQ | InRangeFlag,
10332 InHole = NE
10333 };
10334
10335 ComparisonResult compare(const llvm::APSInt &Value) const {
10336 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10337 Value.isUnsigned() == PromotedMin.isUnsigned());
10338 if (!isContiguous()) {
10339 assert(Value.isUnsigned() && "discontiguous range for signed compare");
10340 if (Value.isMinValue()) return Min;
10341 if (Value.isMaxValue()) return Max;
10342 if (Value >= PromotedMin) return InRange;
10343 if (Value <= PromotedMax) return InRange;
10344 return InHole;
10345 }
10346
10347 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10348 case -1: return Less;
10349 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10350 case 1:
10351 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10352 case -1: return InRange;
10353 case 0: return Max;
10354 case 1: return Greater;
10355 }
10356 }
10357
10358 llvm_unreachable("impossible compare result");
10359 }
10360
Richard Smithc70f1d62017-12-14 15:16:18 +000010361 static llvm::Optional<StringRef>
10362 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10363 if (Op == BO_Cmp) {
10364 ComparisonResult LTFlag = LT, GTFlag = GT;
10365 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10366
10367 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10368 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10369 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10370 return llvm::None;
10371 }
10372
Richard Smitha5370fb2017-12-08 22:57:11 +000010373 ComparisonResult TrueFlag, FalseFlag;
10374 if (Op == BO_EQ) {
10375 TrueFlag = EQ;
10376 FalseFlag = NE;
10377 } else if (Op == BO_NE) {
10378 TrueFlag = NE;
10379 FalseFlag = EQ;
10380 } else {
10381 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10382 TrueFlag = LT;
10383 FalseFlag = GE;
10384 } else {
10385 TrueFlag = GT;
10386 FalseFlag = LE;
10387 }
10388 if (Op == BO_GE || Op == BO_LE)
10389 std::swap(TrueFlag, FalseFlag);
10390 }
10391 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +000010392 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +000010393 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +000010394 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +000010395 return llvm::None;
10396 }
Roman Lebedev6de129e2017-10-15 20:13:17 +000010397};
John McCallcc7e5bf2010-05-06 08:58:33 +000010398}
10399
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010400static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +000010401 // Strip off implicit integral promotions.
10402 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +000010403 if (ICE->getCastKind() != CK_IntegralCast &&
10404 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +000010405 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +000010406 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +000010407 }
10408
10409 return E->getType()->isEnumeralType();
10410}
10411
Richard Smith692f66ab2017-12-06 19:23:19 +000010412static int classifyConstantValue(Expr *Constant) {
10413 // The values of this enumeration are used in the diagnostics
10414 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10415 enum ConstantValueKind {
10416 Miscellaneous = 0,
10417 LiteralTrue,
10418 LiteralFalse
10419 };
10420 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10421 return BL->getValue() ? ConstantValueKind::LiteralTrue
10422 : ConstantValueKind::LiteralFalse;
10423 return ConstantValueKind::Miscellaneous;
10424}
10425
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010426static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10427 Expr *Constant, Expr *Other,
10428 const llvm::APSInt &Value,
10429 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010430 if (S.inTemplateInstantiation())
10431 return false;
10432
Richard Smitha5370fb2017-12-08 22:57:11 +000010433 Expr *OriginalOther = Other;
10434
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010435 Constant = Constant->IgnoreParenImpCasts();
10436 Other = Other->IgnoreParenImpCasts();
10437
Richard Smitha5370fb2017-12-08 22:57:11 +000010438 // Suppress warnings on tautological comparisons between values of the same
10439 // enumeration type. There are only two ways we could warn on this:
10440 // - If the constant is outside the range of representable values of
10441 // the enumeration. In such a case, we should warn about the cast
10442 // to enumeration type, not about the comparison.
10443 // - If the constant is the maximum / minimum in-range value. For an
10444 // enumeratin type, such comparisons can be meaningful and useful.
10445 if (Constant->getType()->isEnumeralType() &&
10446 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10447 return false;
10448
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010449 // TODO: Investigate using GetExprRange() to get tighter bounds
10450 // on the bit ranges.
10451 QualType OtherT = Other->getType();
10452 if (const auto *AT = OtherT->getAs<AtomicType>())
10453 OtherT = AT->getValueType();
10454 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10455
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010456 // Special case for ObjC BOOL on targets where its a typedef for a signed char
10457 // (Namely, macOS).
10458 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10459 S.NSAPIObj->isObjCBOOLType(OtherT) &&
10460 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10461
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010462 // Whether we're treating Other as being a bool because of the form of
10463 // expression despite it having another type (typically 'int' in C).
10464 bool OtherIsBooleanDespiteType =
10465 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010466 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010467 OtherRange = IntRange::forBoolType();
10468
Richard Smitha5370fb2017-12-08 22:57:11 +000010469 // Determine the promoted range of the other type and see if a comparison of
10470 // the constant against that range is tautological.
10471 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10472 Value.isUnsigned());
10473 auto Cmp = OtherPromotedRange.compare(Value);
10474 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10475 if (!Result)
10476 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +000010477
Richard Smitha5370fb2017-12-08 22:57:11 +000010478 // Suppress the diagnostic for an in-range comparison if the constant comes
10479 // from a macro or enumerator. We don't want to diagnose
10480 //
10481 // some_long_value <= INT_MAX
10482 //
10483 // when sizeof(int) == sizeof(long).
10484 bool InRange = Cmp & PromotedRange::InRangeFlag;
10485 if (InRange && IsEnumConstOrFromMacro(S, Constant))
10486 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010487
10488 // If this is a comparison to an enum constant, include that
10489 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +000010490 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010491 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10492 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10493
Richard Smitha5370fb2017-12-08 22:57:11 +000010494 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010495 SmallString<64> PrettySourceValue;
10496 llvm::raw_svector_ostream OS(PrettySourceValue);
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010497 if (ED) {
Ted Kremeneke943ce12013-03-15 22:02:46 +000010498 OS << '\'' << *ED << "' (" << Value << ")";
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010499 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10500 Constant->IgnoreParenImpCasts())) {
10501 OS << (BL->getValue() ? "YES" : "NO");
10502 } else {
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010503 OS << Value;
Erik Pilkingtonfa591c32019-07-08 23:42:52 +000010504 }
10505
10506 if (IsObjCSignedCharBool) {
10507 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10508 S.PDiag(diag::warn_tautological_compare_objc_bool)
10509 << OS.str() << *Result);
10510 return true;
10511 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010512
Richard Smitha5370fb2017-12-08 22:57:11 +000010513 // FIXME: We use a somewhat different formatting for the in-range cases and
10514 // cases involving boolean values for historical reasons. We should pick a
10515 // consistent way of presenting these diagnostics.
10516 if (!InRange || Other->isKnownToHaveBooleanValue()) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010517
Richard Smitha5370fb2017-12-08 22:57:11 +000010518 S.DiagRuntimeBehavior(
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010519 E->getOperatorLoc(), E,
10520 S.PDiag(!InRange ? diag::warn_out_of_range_compare
10521 : diag::warn_tautological_bool_compare)
10522 << OS.str() << classifyConstantValue(Constant) << OtherT
10523 << OtherIsBooleanDespiteType << *Result
10524 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Richard Smitha5370fb2017-12-08 22:57:11 +000010525 } else {
10526 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10527 ? (HasEnumType(OriginalOther)
10528 ? diag::warn_unsigned_enum_always_true_comparison
10529 : diag::warn_unsigned_always_true_comparison)
10530 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +000010531
Richard Smitha5370fb2017-12-08 22:57:11 +000010532 S.Diag(E->getOperatorLoc(), Diag)
10533 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10534 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10535 }
10536
10537 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010538}
10539
John McCallcc7e5bf2010-05-06 08:58:33 +000010540/// Analyze the operands of the given comparison. Implements the
10541/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010542static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +000010543 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10544 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010545}
John McCall263a48b2010-01-04 23:31:57 +000010546
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010547/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +000010548///
Richard Trieu82402a02011-09-15 21:56:47 +000010549/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010550static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010551 // The type the comparison is being performed in.
10552 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +000010553
10554 // Only analyze comparison operators where both sides have been converted to
10555 // the same type.
10556 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10557 return AnalyzeImpConvsInComparison(S, E);
10558
10559 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +000010560 if (E->isValueDependent())
10561 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010562
Roman Lebedev6de129e2017-10-15 20:13:17 +000010563 Expr *LHS = E->getLHS();
10564 Expr *RHS = E->getRHS();
10565
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010566 if (T->isIntegralType(S.Context)) {
10567 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010568 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010569
Roman Lebedev6de129e2017-10-15 20:13:17 +000010570 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10571 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +000010572
Roman Lebedev6de129e2017-10-15 20:13:17 +000010573 // We don't care about expressions whose result is a constant.
10574 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10575 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +000010576
Roman Lebedev6de129e2017-10-15 20:13:17 +000010577 // We only care about expressions where just one side is literal
10578 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10579 // Is the constant on the RHS or LHS?
10580 const bool RhsConstant = IsRHSIntegralLiteral;
10581 Expr *Const = RhsConstant ? RHS : LHS;
10582 Expr *Other = RhsConstant ? LHS : RHS;
10583 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10584
10585 // Check whether an integer constant comparison results in a value
10586 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +000010587 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10588 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010589 }
10590 }
10591
10592 if (!T->hasUnsignedIntegerRepresentation()) {
10593 // We don't do anything special if this isn't an unsigned integral
10594 // comparison: we're only interested in integral comparisons, and
10595 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +000010596 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010597 }
10598
10599 LHS = LHS->IgnoreParenImpCasts();
10600 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010601
Alex Lorenzb57409f2018-02-07 20:45:39 +000010602 if (!S.getLangOpts().CPlusPlus) {
10603 // Avoid warning about comparison of integers with different signs when
10604 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10605 // the type of `E`.
10606 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10607 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10608 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10609 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10610 }
10611
John McCallcc7e5bf2010-05-06 08:58:33 +000010612 // Check to see if one of the (unmodified) operands is of different
10613 // signedness.
10614 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +000010615 if (LHS->getType()->hasSignedIntegerRepresentation()) {
10616 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +000010617 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +000010618 signedOperand = LHS;
10619 unsignedOperand = RHS;
10620 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10621 signedOperand = RHS;
10622 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +000010623 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +000010624 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010625 }
10626
John McCallcc7e5bf2010-05-06 08:58:33 +000010627 // Otherwise, calculate the effective range of the signed operand.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010628 IntRange signedRange =
10629 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
John McCall70aa5392010-01-06 05:24:50 +000010630
John McCallcc7e5bf2010-05-06 08:58:33 +000010631 // Go ahead and analyze implicit conversions in the operands. Note
10632 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +000010633 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10634 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +000010635
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010636 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +000010637 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010638 return;
John McCallca01b222010-01-04 23:21:16 +000010639
10640 // For (in)equality comparisons, if the unsigned operand is a
10641 // constant which cannot collide with a overflowed signed operand,
10642 // then reinterpreting the signed operand as unsigned will not
10643 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +000010644 if (E->isEqualityOp()) {
10645 unsigned comparisonWidth = S.Context.getIntWidth(T);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010646 IntRange unsignedRange =
10647 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
John McCallca01b222010-01-04 23:21:16 +000010648
John McCallcc7e5bf2010-05-06 08:58:33 +000010649 // We should never be unable to prove that the unsigned operand is
10650 // non-negative.
10651 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10652
10653 if (unsignedRange.Width < comparisonWidth)
10654 return;
10655 }
10656
Douglas Gregorbfb4a212012-05-01 01:53:49 +000010657 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010658 S.PDiag(diag::warn_mixed_sign_comparison)
10659 << LHS->getType() << RHS->getType()
10660 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +000010661}
10662
John McCall1f425642010-11-11 03:21:53 +000010663/// Analyzes an attempt to assign the given value to a bitfield.
10664///
10665/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010666static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10667 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +000010668 assert(Bitfield->isBitField());
10669 if (Bitfield->isInvalidDecl())
10670 return false;
10671
John McCalldeebbcf2010-11-11 05:33:51 +000010672 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +000010673 QualType BitfieldType = Bitfield->getType();
10674 if (BitfieldType->isBooleanType())
10675 return false;
10676
10677 if (BitfieldType->isEnumeralType()) {
10678 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10679 // If the underlying enum type was not explicitly specified as an unsigned
10680 // type and the enum contain only positive values, MSVC++ will cause an
10681 // inconsistency by storing this as a signed type.
10682 if (S.getLangOpts().CPlusPlus11 &&
10683 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10684 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10685 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10686 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10687 << BitfieldEnumDecl->getNameAsString();
10688 }
10689 }
10690
John McCalldeebbcf2010-11-11 05:33:51 +000010691 if (Bitfield->getType()->isBooleanType())
10692 return false;
10693
Douglas Gregor789adec2011-02-04 13:09:01 +000010694 // Ignore value- or type-dependent expressions.
10695 if (Bitfield->getBitWidth()->isValueDependent() ||
10696 Bitfield->getBitWidth()->isTypeDependent() ||
10697 Init->isValueDependent() ||
10698 Init->isTypeDependent())
10699 return false;
10700
John McCall1f425642010-11-11 03:21:53 +000010701 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +000010702 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +000010703
Fangrui Song407659a2018-11-30 23:41:18 +000010704 Expr::EvalResult Result;
10705 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
Reid Kleckner329f24d2017-03-14 18:01:02 +000010706 Expr::SE_AllowSideEffects)) {
10707 // The RHS is not constant. If the RHS has an enum type, make sure the
10708 // bitfield is wide enough to hold all the values of the enum without
10709 // truncation.
10710 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10711 EnumDecl *ED = EnumTy->getDecl();
10712 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10713
10714 // Enum types are implicitly signed on Windows, so check if there are any
10715 // negative enumerators to see if the enum was intended to be signed or
10716 // not.
10717 bool SignedEnum = ED->getNumNegativeBits() > 0;
10718
10719 // Check for surprising sign changes when assigning enum values to a
10720 // bitfield of different signedness. If the bitfield is signed and we
10721 // have exactly the right number of bits to store this unsigned enum,
10722 // suggest changing the enum to an unsigned type. This typically happens
10723 // on Windows where unfixed enums always use an underlying type of 'int'.
10724 unsigned DiagID = 0;
10725 if (SignedEnum && !SignedBitfield) {
10726 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10727 } else if (SignedBitfield && !SignedEnum &&
10728 ED->getNumPositiveBits() == FieldWidth) {
10729 DiagID = diag::warn_signed_bitfield_enum_conversion;
10730 }
10731
10732 if (DiagID) {
10733 S.Diag(InitLoc, DiagID) << Bitfield << ED;
10734 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10735 SourceRange TypeRange =
10736 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10737 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10738 << SignedEnum << TypeRange;
10739 }
10740
10741 // Compute the required bitwidth. If the enum has negative values, we need
10742 // one more bit than the normal number of positive bits to represent the
10743 // sign bit.
10744 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10745 ED->getNumNegativeBits())
10746 : ED->getNumPositiveBits();
10747
10748 // Check the bitwidth.
10749 if (BitsNeeded > FieldWidth) {
10750 Expr *WidthExpr = Bitfield->getBitWidth();
10751 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10752 << Bitfield << ED;
10753 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10754 << BitsNeeded << ED << WidthExpr->getSourceRange();
10755 }
10756 }
10757
John McCall1f425642010-11-11 03:21:53 +000010758 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +000010759 }
John McCall1f425642010-11-11 03:21:53 +000010760
Fangrui Song407659a2018-11-30 23:41:18 +000010761 llvm::APSInt Value = Result.Val.getInt();
10762
John McCall1f425642010-11-11 03:21:53 +000010763 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +000010764
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010765 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +000010766 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010767 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10768 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +000010769
John McCall1f425642010-11-11 03:21:53 +000010770 if (OriginalWidth <= FieldWidth)
10771 return false;
10772
Eli Friedmanc267a322012-01-26 23:11:39 +000010773 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +000010774 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +000010775 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +000010776
Eli Friedmanc267a322012-01-26 23:11:39 +000010777 // Check whether the stored value is equal to the original value.
10778 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +000010779 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +000010780 return false;
10781
Eli Friedmanc267a322012-01-26 23:11:39 +000010782 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +000010783 // therefore don't strictly fit into a signed bitfield of width 1.
10784 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +000010785 return false;
10786
John McCall1f425642010-11-11 03:21:53 +000010787 std::string PrettyValue = Value.toString(10);
10788 std::string PrettyTrunc = TruncatedValue.toString(10);
10789
10790 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10791 << PrettyValue << PrettyTrunc << OriginalInit->getType()
10792 << Init->getSourceRange();
10793
10794 return true;
10795}
10796
John McCalld2a53122010-11-09 23:24:47 +000010797/// Analyze the given simple or compound assignment for warning-worthy
10798/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010799static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +000010800 // Just recurse on the LHS.
10801 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10802
10803 // We want to recurse on the RHS as normal unless we're assigning to
10804 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +000010805 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010806 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +000010807 E->getOperatorLoc())) {
10808 // Recurse, ignoring any implicit conversions on the RHS.
10809 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10810 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +000010811 }
10812 }
10813
10814 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
Richard Smith6822bd72018-10-26 19:26:45 +000010815
JF Bastiene77b48b2018-09-10 20:42:56 +000010816 // Diagnose implicitly sequentially-consistent atomic assignment.
10817 if (E->getLHS()->getType()->isAtomicType())
10818 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCalld2a53122010-11-09 23:24:47 +000010819}
10820
John McCall263a48b2010-01-04 23:31:57 +000010821/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Fangrui Song6907ce22018-07-30 19:24:48 +000010822static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010823 SourceLocation CContext, unsigned diag,
10824 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010825 if (pruneControlFlow) {
10826 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10827 S.PDiag(diag)
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000010828 << SourceType << T << E->getSourceRange()
10829 << SourceRange(CContext));
Anna Zaks314cd092012-02-01 19:08:57 +000010830 return;
10831 }
Douglas Gregor364f7db2011-03-12 00:14:31 +000010832 S.Diag(E->getExprLoc(), diag)
10833 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10834}
10835
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010836/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010837static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10838 SourceLocation CContext,
10839 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010840 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010841}
10842
Richard Trieube234c32016-04-21 21:04:55 +000010843/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010844static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10845 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +000010846 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +000010847 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +000010848
10849 Expr *InnerE = E->IgnoreParenImpCasts();
10850 // We also want to warn on, e.g., "int i = -1.234"
10851 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10852 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10853 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10854
10855 const bool IsLiteral =
10856 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10857
10858 llvm::APFloat Value(0.0);
10859 bool IsConstant =
10860 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10861 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +000010862 return DiagnoseImpCast(S, E, T, CContext,
10863 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +000010864 }
10865
Chandler Carruth016ef402011-04-10 08:36:24 +000010866 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +000010867
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +000010868 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10869 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +000010870 llvm::APFloat::opStatus Result = Value.convertToInteger(
10871 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10872
10873 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +000010874 if (IsLiteral) return;
10875 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10876 PruneWarnings);
10877 }
10878
Erich Keanea4c48c62018-05-08 21:26:21 +000010879 // Conversion of a floating-point value to a non-bool integer where the
10880 // integral part cannot be represented by the integer type is undefined.
10881 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10882 return DiagnoseImpCast(
10883 S, E, T, CContext,
10884 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +000010885 : diag::warn_impcast_float_to_integer_out_of_range,
10886 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +000010887
Richard Trieube234c32016-04-21 21:04:55 +000010888 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +000010889 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +000010890 // Warn on floating point literal to integer.
10891 DiagID = diag::warn_impcast_literal_float_to_integer;
10892 } else if (IntegerValue == 0) {
10893 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
10894 return DiagnoseImpCast(S, E, T, CContext,
10895 diag::warn_impcast_float_integer, PruneWarnings);
10896 }
10897 // Warn on non-zero to zero conversion.
10898 DiagID = diag::warn_impcast_float_to_integer_zero;
10899 } else {
10900 if (IntegerValue.isUnsigned()) {
10901 if (!IntegerValue.isMaxValue()) {
10902 return DiagnoseImpCast(S, E, T, CContext,
10903 diag::warn_impcast_float_integer, PruneWarnings);
10904 }
10905 } else { // IntegerValue.isSigned()
10906 if (!IntegerValue.isMaxSignedValue() &&
10907 !IntegerValue.isMinSignedValue()) {
10908 return DiagnoseImpCast(S, E, T, CContext,
10909 diag::warn_impcast_float_integer, PruneWarnings);
10910 }
10911 }
10912 // Warn on evaluatable floating point expression to integer conversion.
10913 DiagID = diag::warn_impcast_float_to_integer;
10914 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010915
David Bolvansky3cc2ef82018-11-14 14:27:51 +000010916 // FIXME: Force the precision of the source value down so we don't print
10917 // digits which are usually useless (we don't really care here if we
10918 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
10919 // would automatically print the shortest representation, but it's a bit
10920 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +000010921 SmallString<16> PrettySourceValue;
David Bolvansky3cc2ef82018-11-14 14:27:51 +000010922 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10923 precision = (precision * 59 + 195) / 196;
10924 Value.toString(PrettySourceValue, precision);
Eli Friedman07185912013-08-29 23:44:43 +000010925
David Blaikie9b88cc02012-05-15 17:18:27 +000010926 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +000010927 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +000010928 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +000010929 else
David Blaikie9b88cc02012-05-15 17:18:27 +000010930 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +000010931
Richard Trieube234c32016-04-21 21:04:55 +000010932 if (PruneWarnings) {
10933 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10934 S.PDiag(DiagID)
10935 << E->getType() << T.getUnqualifiedType()
10936 << PrettySourceValue << PrettyTargetValue
10937 << E->getSourceRange() << SourceRange(CContext));
10938 } else {
10939 S.Diag(E->getExprLoc(), DiagID)
10940 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10941 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10942 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010943}
10944
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010945/// Analyze the given compound assignment for the possible losing of
10946/// floating-point precision.
10947static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10948 assert(isa<CompoundAssignOperator>(E) &&
10949 "Must be compound assignment operation");
10950 // Recurse on the LHS and RHS in here
10951 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10952 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10953
JF Bastiene77b48b2018-09-10 20:42:56 +000010954 if (E->getLHS()->getType()->isAtomicType())
10955 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10956
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010957 // Now check the outermost expression
10958 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10959 const auto *RBT = cast<CompoundAssignOperator>(E)
10960 ->getComputationResultType()
10961 ->getAs<BuiltinType>();
10962
10963 // The below checks assume source is floating point.
10964 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10965
Erik Pilkingtond5b017d2019-02-14 22:48:01 +000010966 // If source is floating point but target is an integer.
10967 if (ResultBT->isInteger())
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +000010968 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10969 E->getExprLoc(), diag::warn_impcast_float_integer);
10970
10971 if (!ResultBT->isFloatingPoint())
10972 return;
10973
10974 // If both source and target are floating points, warn about losing precision.
10975 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10976 QualType(ResultBT, 0), QualType(RBT, 0));
10977 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010978 // warn about dropping FP rank.
10979 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10980 diag::warn_impcast_float_result_precision);
10981}
10982
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010983static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10984 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +000010985 if (!Range.Width) return "0";
10986
10987 llvm::APSInt ValueInRange = Value;
10988 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +000010989 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +000010990 return ValueInRange.toString(10);
10991}
10992
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010993static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010994 if (!isa<ImplicitCastExpr>(Ex))
10995 return false;
10996
10997 Expr *InnerE = Ex->IgnoreParenImpCasts();
10998 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10999 const Type *Source =
11000 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11001 if (Target->isDependentType())
11002 return false;
11003
11004 const BuiltinType *FloatCandidateBT =
11005 dyn_cast<BuiltinType>(ToBool ? Source : Target);
11006 const Type *BoolCandidateType = ToBool ? Target : Source;
11007
11008 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11009 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11010}
11011
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011012static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11013 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011014 unsigned NumArgs = TheCall->getNumArgs();
11015 for (unsigned i = 0; i < NumArgs; ++i) {
11016 Expr *CurrA = TheCall->getArg(i);
11017 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11018 continue;
11019
11020 bool IsSwapped = ((i > 0) &&
11021 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11022 IsSwapped |= ((i < (NumArgs - 1)) &&
11023 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11024 if (IsSwapped) {
11025 // Warn on this floating-point to bool conversion.
11026 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11027 CurrA->getType(), CC,
11028 diag::warn_impcast_floating_point_to_bool);
11029 }
11030 }
11031}
11032
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011033static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11034 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +000011035 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11036 E->getExprLoc()))
11037 return;
11038
Richard Trieu09d6b802016-01-08 23:35:06 +000011039 // Don't warn on functions which have return type nullptr_t.
11040 if (isa<CallExpr>(E))
11041 return;
11042
Richard Trieu5b993502014-10-15 03:42:06 +000011043 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11044 const Expr::NullPointerConstantKind NullKind =
11045 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11046 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11047 return;
11048
11049 // Return if target type is a safe conversion.
11050 if (T->isAnyPointerType() || T->isBlockPointerType() ||
11051 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11052 return;
11053
11054 SourceLocation Loc = E->getSourceRange().getBegin();
11055
Richard Trieu0a5e1662016-02-13 00:58:53 +000011056 // Venture through the macro stacks to get to the source of macro arguments.
11057 // The new location is a better location than the complete location that was
11058 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +000011059 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11060 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +000011061
Richard Trieu5b993502014-10-15 03:42:06 +000011062 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +000011063 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11064 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11065 Loc, S.SourceMgr, S.getLangOpts());
11066 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +000011067 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +000011068 }
11069
11070 // Only warn if the null and context location are in the same macro expansion.
11071 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11072 return;
11073
11074 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011075 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000011076 << FixItHint::CreateReplacement(Loc,
11077 S.getFixItZeroLiteralForType(T, Loc));
11078}
11079
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011080static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11081 ObjCArrayLiteral *ArrayLiteral);
11082
11083static void
11084checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11085 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000011086
11087/// Check a single element within a collection literal against the
11088/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011089static void checkObjCCollectionLiteralElement(Sema &S,
11090 QualType TargetElementType,
11091 Expr *Element,
11092 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000011093 // Skip a bitcast to 'id' or qualified 'id'.
11094 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11095 if (ICE->getCastKind() == CK_BitCast &&
11096 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11097 Element = ICE->getSubExpr();
11098 }
11099
11100 QualType ElementType = Element->getType();
11101 ExprResult ElementResult(Element);
11102 if (ElementType->getAs<ObjCObjectPointerType>() &&
11103 S.CheckSingleAssignmentConstraints(TargetElementType,
11104 ElementResult,
11105 false, false)
11106 != Sema::Compatible) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011107 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11108 << ElementType << ElementKind << TargetElementType
11109 << Element->getSourceRange();
Douglas Gregor5054cb02015-07-07 03:58:22 +000011110 }
11111
11112 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11113 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11114 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11115 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11116}
11117
11118/// Check an Objective-C array literal being converted to the given
11119/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011120static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11121 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000011122 if (!S.NSArrayDecl)
11123 return;
11124
11125 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11126 if (!TargetObjCPtr)
11127 return;
11128
11129 if (TargetObjCPtr->isUnspecialized() ||
11130 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11131 != S.NSArrayDecl->getCanonicalDecl())
11132 return;
11133
11134 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11135 if (TypeArgs.size() != 1)
11136 return;
11137
11138 QualType TargetElementType = TypeArgs[0];
11139 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11140 checkObjCCollectionLiteralElement(S, TargetElementType,
11141 ArrayLiteral->getElement(I),
11142 0);
11143 }
11144}
11145
11146/// Check an Objective-C dictionary literal being converted to the given
11147/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011148static void
11149checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11150 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000011151 if (!S.NSDictionaryDecl)
11152 return;
11153
11154 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11155 if (!TargetObjCPtr)
11156 return;
11157
11158 if (TargetObjCPtr->isUnspecialized() ||
11159 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11160 != S.NSDictionaryDecl->getCanonicalDecl())
11161 return;
11162
11163 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11164 if (TypeArgs.size() != 2)
11165 return;
11166
11167 QualType TargetKeyType = TypeArgs[0];
11168 QualType TargetObjectType = TypeArgs[1];
11169 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11170 auto Element = DictionaryLiteral->getKeyValueElement(I);
11171 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11172 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11173 }
11174}
11175
Richard Trieufc404c72016-02-05 23:02:38 +000011176// Helper function to filter out cases for constant width constant conversion.
11177// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011178static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11179 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000011180 // If initializing from a constant, and the constant starts with '0',
11181 // then it is a binary, octal, or hexadecimal. Allow these constants
11182 // to fill all the bits, even if there is a sign change.
11183 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11184 const char FirstLiteralCharacter =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011185 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
Richard Trieufc404c72016-02-05 23:02:38 +000011186 if (FirstLiteralCharacter == '0')
11187 return false;
11188 }
11189
11190 // If the CC location points to a '{', and the type is char, then assume
11191 // assume it is an array initialization.
11192 if (CC.isValid() && T->isCharType()) {
11193 const char FirstContextCharacter =
11194 S.getSourceManager().getCharacterData(CC)[0];
11195 if (FirstContextCharacter == '{')
11196 return false;
11197 }
11198
11199 return true;
11200}
11201
Erik Pilkingtonabffae3a52019-07-09 17:29:40 +000011202static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11203 return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11204 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11205}
11206
Ziang Wan87b668b2019-08-01 00:16:43 +000011207static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11208 SourceLocation CC,
11209 bool *ICContext = nullptr,
11210 bool IsListInit = false) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011211 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000011212
John McCallcc7e5bf2010-05-06 08:58:33 +000011213 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11214 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11215 if (Source == Target) return;
11216 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000011217
Chandler Carruthc22845a2011-07-26 05:40:03 +000011218 // If the conversion context location is invalid don't complain. We also
11219 // don't want to emit a warning if the issue occurs from the expansion of
11220 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11221 // delay this check as long as possible. Once we detect we are in that
11222 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011223 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000011224 return;
11225
JF Bastiene77b48b2018-09-10 20:42:56 +000011226 if (Source->isAtomicType())
11227 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11228
Richard Trieu021baa32011-09-23 20:10:00 +000011229 // Diagnose implicit casts to bool.
11230 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11231 if (isa<StringLiteral>(E))
11232 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000011233 // and expressions, for instance, assert(0 && "error here"), are
11234 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000011235 return DiagnoseImpCast(S, E, T, CC,
11236 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000011237 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11238 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11239 // This covers the literal expressions that evaluate to Objective-C
11240 // objects.
11241 return DiagnoseImpCast(S, E, T, CC,
11242 diag::warn_impcast_objective_c_literal_to_bool);
11243 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000011244 if (Source->isPointerType() || Source->canDecayToPointerType()) {
11245 // Warn on pointer to bool conversion that is always true.
11246 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11247 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000011248 }
Richard Trieu021baa32011-09-23 20:10:00 +000011249 }
John McCall263a48b2010-01-04 23:31:57 +000011250
Erik Pilkingtonabffae3a52019-07-09 17:29:40 +000011251 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11252 // is a typedef for signed char (macOS), then that constant value has to be 1
11253 // or 0.
11254 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11255 Expr::EvalResult Result;
11256 if (E->EvaluateAsInt(Result, S.getASTContext(),
11257 Expr::SE_AllowSideEffects) &&
11258 Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11259 auto Builder = S.Diag(CC, diag::warn_impcast_constant_int_to_objc_bool)
11260 << Result.Val.getInt().toString(10);
11261 Expr *Ignored = E->IgnoreImplicit();
11262 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11263 isa<BinaryOperator>(Ignored) ||
11264 isa<CXXOperatorCallExpr>(Ignored);
11265 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
11266 if (NeedsParens)
11267 Builder << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
11268 << FixItHint::CreateInsertion(EndLoc, ")");
11269 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11270 return;
11271 }
11272 }
11273
Douglas Gregor5054cb02015-07-07 03:58:22 +000011274 // Check implicit casts from Objective-C collection literals to specialized
11275 // collection types, e.g., NSArray<NSString *> *.
11276 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11277 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11278 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11279 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11280
John McCall263a48b2010-01-04 23:31:57 +000011281 // Strip vector types.
11282 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011283 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011284 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011285 return;
John McCallacf0ee52010-10-08 02:01:28 +000011286 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011287 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011288
Chris Lattneree7286f2011-06-14 04:51:15 +000011289 // If the vector cast is cast between two vectors of the same size, it is
11290 // a bitcast, not a conversion.
11291 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11292 return;
John McCall263a48b2010-01-04 23:31:57 +000011293
11294 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11295 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11296 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000011297 if (auto VecTy = dyn_cast<VectorType>(Target))
11298 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000011299
11300 // Strip complex types.
11301 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011302 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000011303 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011304 return;
11305
Tim Northover02416372017-08-08 23:18:05 +000011306 return DiagnoseImpCast(S, E, T, CC,
11307 S.getLangOpts().CPlusPlus
11308 ? diag::err_impcast_complex_scalar
11309 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011310 }
John McCall263a48b2010-01-04 23:31:57 +000011311
11312 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11313 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11314 }
11315
11316 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11317 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11318
11319 // If the source is floating point...
11320 if (SourceBT && SourceBT->isFloatingPoint()) {
11321 // ...and the target is floating point...
11322 if (TargetBT && TargetBT->isFloatingPoint()) {
11323 // ...then warn if we're dropping FP rank.
11324
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +000011325 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11326 QualType(SourceBT, 0), QualType(TargetBT, 0));
11327 if (Order > 0) {
John McCall263a48b2010-01-04 23:31:57 +000011328 // Don't warn about float constants that are precisely
11329 // representable in the target type.
11330 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000011331 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000011332 // Value might be a float, a float vector, or a float complex.
11333 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000011334 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11335 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000011336 return;
11337 }
11338
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011339 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011340 return;
11341
John McCallacf0ee52010-10-08 02:01:28 +000011342 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000011343 }
11344 // ... or possibly if we're increasing rank, too
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +000011345 else if (Order < 0) {
George Burgess IV148e0d32015-10-29 00:28:52 +000011346 if (S.SourceMgr.isInSystemMacro(CC))
11347 return;
11348
11349 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000011350 }
11351 return;
11352 }
11353
Richard Trieube234c32016-04-21 21:04:55 +000011354 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000011355 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011356 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011357 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000011358
Richard Trieube234c32016-04-21 21:04:55 +000011359 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000011360 }
John McCall263a48b2010-01-04 23:31:57 +000011361
Richard Smith54894fd2015-12-30 01:06:52 +000011362 // Detect the case where a call result is converted from floating-point to
11363 // to bool, and the final argument to the call is converted from bool, to
11364 // discover this typo:
11365 //
11366 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
11367 //
11368 // FIXME: This is an incredibly special case; is there some more general
11369 // way to detect this class of misplaced-parentheses bug?
11370 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011371 // Check last argument of function call to see if it is an
11372 // implicit cast from a type matching the type the result
11373 // is being cast to.
11374 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000011375 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011376 Expr *LastA = CEx->getArg(NumArgs - 1);
11377 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000011378 if (isa<ImplicitCastExpr>(LastA) &&
11379 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011380 // Warn on this floating-point to bool conversion
11381 DiagnoseImpCast(S, E, T, CC,
11382 diag::warn_impcast_floating_point_to_bool);
11383 }
11384 }
11385 }
John McCall263a48b2010-01-04 23:31:57 +000011386 return;
11387 }
11388
Leonard Chan8f7caae2019-03-06 00:28:43 +000011389 // Valid casts involving fixed point types should be accounted for here.
Leonard Chand3f3e162019-01-18 21:04:25 +000011390 if (Source->isFixedPointType()) {
Leonard Chan8f7caae2019-03-06 00:28:43 +000011391 if (Target->isUnsaturatedFixedPointType()) {
Leonard Chand3f3e162019-01-18 21:04:25 +000011392 Expr::EvalResult Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011393 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11394 S.isConstantEvaluated())) {
Leonard Chand3f3e162019-01-18 21:04:25 +000011395 APFixedPoint Value = Result.Val.getFixedPoint();
11396 APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11397 APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11398 if (Value > MaxVal || Value < MinVal) {
11399 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11400 S.PDiag(diag::warn_impcast_fixed_point_range)
11401 << Value.toString() << T
11402 << E->getSourceRange()
11403 << clang::SourceRange(CC));
11404 return;
11405 }
11406 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000011407 } else if (Target->isIntegerType()) {
11408 Expr::EvalResult Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011409 if (!S.isConstantEvaluated() &&
11410 E->EvaluateAsFixedPoint(Result, S.Context,
Leonard Chan8f7caae2019-03-06 00:28:43 +000011411 Expr::SE_AllowSideEffects)) {
11412 APFixedPoint FXResult = Result.Val.getFixedPoint();
11413
11414 bool Overflowed;
11415 llvm::APSInt IntResult = FXResult.convertToInt(
11416 S.Context.getIntWidth(T),
11417 Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11418
11419 if (Overflowed) {
11420 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11421 S.PDiag(diag::warn_impcast_fixed_point_range)
11422 << FXResult.toString() << T
11423 << E->getSourceRange()
11424 << clang::SourceRange(CC));
11425 return;
11426 }
11427 }
11428 }
11429 } else if (Target->isUnsaturatedFixedPointType()) {
11430 if (Source->isIntegerType()) {
11431 Expr::EvalResult Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011432 if (!S.isConstantEvaluated() &&
11433 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
Leonard Chan8f7caae2019-03-06 00:28:43 +000011434 llvm::APSInt Value = Result.Val.getInt();
11435
11436 bool Overflowed;
11437 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11438 Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11439
11440 if (Overflowed) {
11441 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11442 S.PDiag(diag::warn_impcast_fixed_point_range)
Rui Ueyama49a3ad22019-07-16 04:46:31 +000011443 << Value.toString(/*Radix=*/10) << T
Leonard Chan8f7caae2019-03-06 00:28:43 +000011444 << E->getSourceRange()
11445 << clang::SourceRange(CC));
11446 return;
11447 }
11448 }
Leonard Chand3f3e162019-01-18 21:04:25 +000011449 }
11450 }
11451
Ziang Wan87b668b2019-08-01 00:16:43 +000011452 // If we are casting an integer type to a floating point type without
11453 // initialization-list syntax, we might lose accuracy if the floating
11454 // point type has a narrower significand than the integer type.
11455 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11456 TargetBT->isFloatingType() && !IsListInit) {
11457 // Determine the number of precision bits in the source integer type.
11458 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11459 unsigned int SourcePrecision = SourceRange.Width;
11460
11461 // Determine the number of precision bits in the
11462 // target floating point type.
11463 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11464 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11465
11466 if (SourcePrecision > 0 && TargetPrecision > 0 &&
11467 SourcePrecision > TargetPrecision) {
11468
11469 llvm::APSInt SourceInt;
11470 if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11471 // If the source integer is a constant, convert it to the target
11472 // floating point type. Issue a warning if the value changes
11473 // during the whole conversion.
11474 llvm::APFloat TargetFloatValue(
11475 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11476 llvm::APFloat::opStatus ConversionStatus =
11477 TargetFloatValue.convertFromAPInt(
11478 SourceInt, SourceBT->isSignedInteger(),
11479 llvm::APFloat::rmNearestTiesToEven);
11480
11481 if (ConversionStatus != llvm::APFloat::opOK) {
11482 std::string PrettySourceValue = SourceInt.toString(10);
11483 SmallString<32> PrettyTargetValue;
11484 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11485
11486 S.DiagRuntimeBehavior(
11487 E->getExprLoc(), E,
11488 S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11489 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11490 << E->getSourceRange() << clang::SourceRange(CC));
11491 }
11492 } else {
11493 // Otherwise, the implicit conversion may lose precision.
11494 DiagnoseImpCast(S, E, T, CC,
11495 diag::warn_impcast_integer_float_precision);
11496 }
11497 }
11498 }
11499
Richard Trieu5b993502014-10-15 03:42:06 +000011500 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000011501
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011502 S.DiscardMisalignedMemberAddress(Target, E);
11503
David Blaikie9366d2b2012-06-19 21:19:06 +000011504 if (!Source->isIntegerType() || !Target->isIntegerType())
11505 return;
11506
David Blaikie7555b6a2012-05-15 16:56:36 +000011507 // TODO: remove this early return once the false positives for constant->bool
11508 // in templates, macros, etc, are reduced or removed.
11509 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11510 return;
11511
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011512 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
John McCall817d4af2010-11-10 23:38:19 +000011513 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000011514
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011515 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000011516 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011517 // TODO: this should happen for bitfield stores, too.
Fangrui Song407659a2018-11-30 23:41:18 +000011518 Expr::EvalResult Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011519 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11520 S.isConstantEvaluated())) {
Fangrui Song407659a2018-11-30 23:41:18 +000011521 llvm::APSInt Value(32);
11522 Value = Result.Val.getInt();
11523
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011524 if (S.SourceMgr.isInSystemMacro(CC))
11525 return;
11526
John McCall18a2c2c2010-11-09 22:22:12 +000011527 std::string PrettySourceValue = Value.toString(10);
11528 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011529
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011530 S.DiagRuntimeBehavior(
11531 E->getExprLoc(), E,
11532 S.PDiag(diag::warn_impcast_integer_precision_constant)
11533 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11534 << E->getSourceRange() << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000011535 return;
11536 }
11537
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011538 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11539 if (S.SourceMgr.isInSystemMacro(CC))
11540 return;
11541
David Blaikie9455da02012-04-12 22:40:54 +000011542 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000011543 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11544 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000011545 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000011546 }
11547
David Bolvanskycf7d2252018-10-02 06:02:30 +000011548 if (TargetRange.Width > SourceRange.Width) {
11549 if (auto *UO = dyn_cast<UnaryOperator>(E))
11550 if (UO->getOpcode() == UO_Minus)
11551 if (Source->isUnsignedIntegerType()) {
11552 if (Target->isUnsignedIntegerType())
11553 return DiagnoseImpCast(S, E, T, CC,
11554 diag::warn_impcast_high_order_zero_bits);
11555 if (Target->isSignedIntegerType())
11556 return DiagnoseImpCast(S, E, T, CC,
11557 diag::warn_impcast_nonnegative_result);
11558 }
11559 }
11560
Richard Trieudcb55572016-01-29 23:51:16 +000011561 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11562 SourceRange.NonNegative && Source->isSignedIntegerType()) {
11563 // Warn when doing a signed to signed conversion, warn if the positive
11564 // source value is exactly the width of the target type, which will
11565 // cause a negative value to be stored.
11566
Fangrui Song407659a2018-11-30 23:41:18 +000011567 Expr::EvalResult Result;
11568 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
Richard Trieufc404c72016-02-05 23:02:38 +000011569 !S.SourceMgr.isInSystemMacro(CC)) {
Fangrui Song407659a2018-11-30 23:41:18 +000011570 llvm::APSInt Value = Result.Val.getInt();
Richard Trieufc404c72016-02-05 23:02:38 +000011571 if (isSameWidthConstantConversion(S, E, T, CC)) {
11572 std::string PrettySourceValue = Value.toString(10);
11573 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000011574
Richard Trieufc404c72016-02-05 23:02:38 +000011575 S.DiagRuntimeBehavior(
11576 E->getExprLoc(), E,
11577 S.PDiag(diag::warn_impcast_integer_precision_constant)
11578 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11579 << E->getSourceRange() << clang::SourceRange(CC));
11580 return;
Richard Trieudcb55572016-01-29 23:51:16 +000011581 }
11582 }
Richard Trieufc404c72016-02-05 23:02:38 +000011583
Richard Trieudcb55572016-01-29 23:51:16 +000011584 // Fall through for non-constants to give a sign conversion warning.
11585 }
11586
John McCallcc7e5bf2010-05-06 08:58:33 +000011587 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11588 (!TargetRange.NonNegative && SourceRange.NonNegative &&
11589 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011590 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011591 return;
11592
John McCallcc7e5bf2010-05-06 08:58:33 +000011593 unsigned DiagID = diag::warn_impcast_integer_sign;
11594
11595 // Traditionally, gcc has warned about this under -Wsign-compare.
11596 // We also want to warn about it in -Wconversion.
11597 // So if -Wconversion is off, use a completely identical diagnostic
11598 // in the sign-compare group.
Fangrui Song6907ce22018-07-30 19:24:48 +000011599 // The conditional-checking code will
John McCallcc7e5bf2010-05-06 08:58:33 +000011600 if (ICContext) {
11601 DiagID = diag::warn_impcast_integer_sign_conditional;
11602 *ICContext = true;
11603 }
11604
John McCallacf0ee52010-10-08 02:01:28 +000011605 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000011606 }
11607
Douglas Gregora78f1932011-02-22 02:45:07 +000011608 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000011609 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11610 // type, to give us better diagnostics.
11611 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011612 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000011613 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11614 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11615 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11616 SourceType = S.Context.getTypeDeclType(Enum);
11617 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11618 }
11619 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011620
Douglas Gregora78f1932011-02-22 02:45:07 +000011621 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11622 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000011623 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11624 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011625 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011626 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011627 return;
11628
Fangrui Song6907ce22018-07-30 19:24:48 +000011629 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000011630 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011631 }
John McCall263a48b2010-01-04 23:31:57 +000011632}
11633
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011634static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11635 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011636
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011637static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11638 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011639 E = E->IgnoreParenImpCasts();
11640
11641 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000011642 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011643
John McCallacf0ee52010-10-08 02:01:28 +000011644 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011645 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011646 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000011647}
11648
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011649static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11650 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000011651 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000011652
11653 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000011654 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11655 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011656
11657 // If -Wconversion would have warned about either of the candidates
11658 // for a signedness conversion to the context type...
11659 if (!Suspicious) return;
11660
11661 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011662 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000011663 return;
11664
John McCallcc7e5bf2010-05-06 08:58:33 +000011665 // ...then check whether it would have warned about either of the
11666 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000011667 if (E->getType() == T) return;
Fangrui Song6907ce22018-07-30 19:24:48 +000011668
Richard Trieubb43dec2011-07-21 02:46:28 +000011669 Suspicious = false;
11670 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11671 E->getType(), CC, &Suspicious);
11672 if (!Suspicious)
11673 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000011674 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011675}
11676
JF Bastiene77b48b2018-09-10 20:42:56 +000011677/// Check conversion of given expression to boolean.
Richard Trieu65724892014-11-15 06:37:39 +000011678/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011679static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000011680 if (S.getLangOpts().Bool)
11681 return;
JF Bastiene77b48b2018-09-10 20:42:56 +000011682 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11683 return;
Richard Trieu65724892014-11-15 06:37:39 +000011684 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11685}
11686
John McCallcc7e5bf2010-05-06 08:58:33 +000011687/// AnalyzeImplicitConversions - Find and report any interesting
11688/// implicit conversions in the given expression. There are a couple
11689/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Ziang Wan87b668b2019-08-01 00:16:43 +000011690static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11691 bool IsListInit/*= false*/) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000011692 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000011693 Expr *E = OrigE->IgnoreParenImpCasts();
11694
Ziang Wan87b668b2019-08-01 00:16:43 +000011695 // Propagate whether we are in a C++ list initialization expression.
11696 // If so, we do not issue warnings for implicit int-float conversion
11697 // precision loss, because C++11 narrowing already handles it.
11698 IsListInit =
11699 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11700
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000011701 if (E->isTypeDependent() || E->isValueDependent())
11702 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011703
John McCallcc7e5bf2010-05-06 08:58:33 +000011704 // For conditional operators, we analyze the arguments as if they
11705 // were being fed directly into the output.
11706 if (isa<ConditionalOperator>(E)) {
11707 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000011708 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011709 return;
11710 }
11711
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011712 // Check implicit argument conversions for function calls.
11713 if (CallExpr *Call = dyn_cast<CallExpr>(E))
11714 CheckImplicitArgumentConversions(S, Call, CC);
11715
John McCallcc7e5bf2010-05-06 08:58:33 +000011716 // Go ahead and check any implicit conversions we might have skipped.
11717 // The non-canonical typecheck is just an optimization;
11718 // CheckImplicitConversion will filter out dead implicit conversions.
11719 if (E->getType() != T)
Ziang Wan87b668b2019-08-01 00:16:43 +000011720 CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
John McCallcc7e5bf2010-05-06 08:58:33 +000011721
11722 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000011723
11724 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11725 // The bound subexpressions in a PseudoObjectExpr are not reachable
11726 // as transitive children.
11727 // FIXME: Use a more uniform representation for this.
11728 for (auto *SE : POE->semantics())
11729 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
Ziang Wan87b668b2019-08-01 00:16:43 +000011730 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000011731 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000011732
John McCallcc7e5bf2010-05-06 08:58:33 +000011733 // Skip past explicit casts.
JF Bastiene77b48b2018-09-10 20:42:56 +000011734 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11735 E = CE->getSubExpr()->IgnoreParenImpCasts();
11736 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11737 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
Ziang Wan87b668b2019-08-01 00:16:43 +000011738 return AnalyzeImplicitConversions(S, E, CC, IsListInit);
John McCallcc7e5bf2010-05-06 08:58:33 +000011739 }
11740
John McCalld2a53122010-11-09 23:24:47 +000011741 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11742 // Do a somewhat different check with comparison operators.
11743 if (BO->isComparisonOp())
11744 return AnalyzeComparison(S, BO);
11745
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011746 // And with simple assignments.
11747 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000011748 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011749 // And with compound assignments.
11750 if (BO->isAssignmentOp())
11751 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000011752 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011753
11754 // These break the otherwise-useful invariant below. Fortunately,
11755 // we don't really need to recurse into them, because any internal
11756 // expressions should have been analyzed already when they were
11757 // built into statements.
11758 if (isa<StmtExpr>(E)) return;
11759
11760 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000011761 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000011762
11763 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000011764 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000011765 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000011766 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000011767 for (Stmt *SubStmt : E->children()) {
11768 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000011769 if (!ChildExpr)
11770 continue;
11771
Richard Trieu955231d2014-01-25 01:10:35 +000011772 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000011773 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000011774 // Ignore checking string literals that are in logical and operators.
11775 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000011776 continue;
Ziang Wan87b668b2019-08-01 00:16:43 +000011777 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
Richard Trieu021baa32011-09-23 20:10:00 +000011778 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011779
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011780 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000011781 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11782 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011783 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000011784
11785 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11786 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011787 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011788 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011789
JF Bastiene77b48b2018-09-10 20:42:56 +000011790 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11791 if (U->getOpcode() == UO_LNot) {
Richard Trieu65724892014-11-15 06:37:39 +000011792 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
JF Bastiene77b48b2018-09-10 20:42:56 +000011793 } else if (U->getOpcode() != UO_AddrOf) {
11794 if (U->getSubExpr()->getType()->isAtomicType())
11795 S.Diag(U->getSubExpr()->getBeginLoc(),
11796 diag::warn_atomic_implicit_seq_cst);
11797 }
11798 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011799}
11800
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011801/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011802static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11803 // Taking into account implicit conversions,
11804 // allow any integer.
11805 if (!E->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011806 S.Diag(E->getBeginLoc(),
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011807 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11808 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011809 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011810 // Potentially emit standard warnings for implicit conversions if enabled
11811 // using -Wconversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011812 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011813 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011814}
11815
Richard Trieuc1888e02014-06-28 23:25:37 +000011816// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11817// Returns true when emitting a warning about taking the address of a reference.
11818static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000011819 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000011820 E = E->IgnoreParenImpCasts();
11821
11822 const FunctionDecl *FD = nullptr;
11823
11824 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11825 if (!DRE->getDecl()->getType()->isReferenceType())
11826 return false;
11827 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11828 if (!M->getMemberDecl()->getType()->isReferenceType())
11829 return false;
11830 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000011831 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000011832 return false;
11833 FD = Call->getDirectCallee();
11834 } else {
11835 return false;
11836 }
11837
11838 SemaRef.Diag(E->getExprLoc(), PD);
11839
11840 // If possible, point to location of function.
11841 if (FD) {
11842 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11843 }
11844
11845 return true;
11846}
11847
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011848// Returns true if the SourceLocation is expanded from any macro body.
11849// Returns false if the SourceLocation is invalid, is from not in a macro
11850// expansion, or is from expanded from a top-level macro argument.
11851static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11852 if (Loc.isInvalid())
11853 return false;
11854
11855 while (Loc.isMacroID()) {
11856 if (SM.isMacroBodyExpansion(Loc))
11857 return true;
11858 Loc = SM.getImmediateMacroCallerLoc(Loc);
11859 }
11860
11861 return false;
11862}
11863
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011864/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000011865/// \param E the expression containing the pointer
11866/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11867/// compared to a null pointer
11868/// \param IsEqual True when the comparison is equal to a null pointer
11869/// \param Range Extra SourceRange to highlight in the diagnostic
11870void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11871 Expr::NullPointerConstantKind NullKind,
11872 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000011873 if (!E)
11874 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011875
11876 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011877 if (E->getExprLoc().isMacroID()) {
11878 const SourceManager &SM = getSourceManager();
11879 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11880 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000011881 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011882 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000011883 E = E->IgnoreImpCasts();
11884
11885 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11886
Richard Trieuf7432752014-06-06 21:39:26 +000011887 if (isa<CXXThisExpr>(E)) {
11888 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11889 : diag::warn_this_bool_conversion;
11890 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11891 return;
11892 }
11893
Richard Trieu3bb8b562014-02-26 02:36:06 +000011894 bool IsAddressOf = false;
11895
11896 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11897 if (UO->getOpcode() != UO_AddrOf)
11898 return;
11899 IsAddressOf = true;
11900 E = UO->getSubExpr();
11901 }
11902
Richard Trieuc1888e02014-06-28 23:25:37 +000011903 if (IsAddressOf) {
11904 unsigned DiagID = IsCompare
11905 ? diag::warn_address_of_reference_null_compare
11906 : diag::warn_address_of_reference_bool_conversion;
11907 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11908 << IsEqual;
11909 if (CheckForReference(*this, E, PD)) {
11910 return;
11911 }
11912 }
11913
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011914 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11915 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000011916 std::string Str;
11917 llvm::raw_string_ostream S(Str);
11918 E->printPretty(S, nullptr, getPrintingPolicy());
11919 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11920 : diag::warn_cast_nonnull_to_bool;
11921 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11922 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011923 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000011924 };
11925
11926 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11927 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11928 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011929 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11930 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011931 return;
11932 }
11933 }
11934 }
11935
Richard Trieu3bb8b562014-02-26 02:36:06 +000011936 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000011937 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011938 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11939 D = R->getDecl();
11940 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11941 D = M->getMemberDecl();
11942 }
11943
11944 // Weak Decls can be null.
11945 if (!D || D->isWeak())
11946 return;
George Burgess IV850269a2015-12-08 22:02:00 +000011947
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011948 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000011949 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11950 if (getCurFunction() &&
11951 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011952 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11953 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011954 return;
11955 }
11956
11957 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
Michael Liaoce389922019-03-29 03:55:52 +000011958 // Skip function template not specialized yet.
11959 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11960 return;
David Majnemera3debed2016-06-24 05:33:44 +000011961 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000011962 assert(ParamIter != FD->param_end());
11963 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11964
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011965 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11966 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011967 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000011968 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011969 }
George Burgess IV850269a2015-12-08 22:02:00 +000011970
Joel E. Denny81508102018-03-13 14:51:22 +000011971 for (const ParamIdx &ArgNo : NonNull->args()) {
11972 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011973 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011974 return;
11975 }
George Burgess IV850269a2015-12-08 22:02:00 +000011976 }
11977 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011978 }
11979 }
George Burgess IV850269a2015-12-08 22:02:00 +000011980 }
11981
Richard Trieu3bb8b562014-02-26 02:36:06 +000011982 QualType T = D->getType();
11983 const bool IsArray = T->isArrayType();
11984 const bool IsFunction = T->isFunctionType();
11985
Richard Trieuc1888e02014-06-28 23:25:37 +000011986 // Address of function is used to silence the function warning.
11987 if (IsAddressOf && IsFunction) {
11988 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011989 }
11990
11991 // Found nothing.
11992 if (!IsAddressOf && !IsFunction && !IsArray)
11993 return;
11994
11995 // Pretty print the expression for the diagnostic.
11996 std::string Str;
11997 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000011998 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000011999
12000 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12001 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000012002 enum {
12003 AddressOf,
12004 FunctionPointer,
12005 ArrayPointer
12006 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000012007 if (IsAddressOf)
12008 DiagType = AddressOf;
12009 else if (IsFunction)
12010 DiagType = FunctionPointer;
12011 else if (IsArray)
12012 DiagType = ArrayPointer;
12013 else
12014 llvm_unreachable("Could not determine diagnostic.");
12015 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12016 << Range << IsEqual;
12017
12018 if (!IsFunction)
12019 return;
12020
12021 // Suggest '&' to silence the function warning.
12022 Diag(E->getExprLoc(), diag::note_function_warning_silence)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012023 << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
Richard Trieu3bb8b562014-02-26 02:36:06 +000012024
12025 // Check to see if '()' fixit should be emitted.
12026 QualType ReturnType;
12027 UnresolvedSet<4> NonTemplateOverloads;
12028 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12029 if (ReturnType.isNull())
12030 return;
12031
12032 if (IsCompare) {
12033 // There are two cases here. If there is null constant, the only suggest
12034 // for a pointer return type. If the null is 0, then suggest if the return
12035 // type is a pointer or an integer type.
12036 if (!ReturnType->isPointerType()) {
12037 if (NullKind == Expr::NPCK_ZeroExpression ||
12038 NullKind == Expr::NPCK_ZeroLiteral) {
12039 if (!ReturnType->isIntegerType())
12040 return;
12041 } else {
12042 return;
12043 }
12044 }
12045 } else { // !IsCompare
12046 // For function to bool, only suggest if the function pointer has bool
12047 // return type.
12048 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12049 return;
12050 }
12051 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Kelly1c301dc2018-08-09 21:09:38 +000012052 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000012053}
12054
John McCallcc7e5bf2010-05-06 08:58:33 +000012055/// Diagnoses "dangerous" implicit conversions within the given
12056/// expression (which is a full expression). Implements -Wconversion
12057/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000012058///
12059/// \param CC the "context" location of the implicit conversion, i.e.
12060/// the most location of the syntactic entity requiring the implicit
12061/// conversion
12062void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000012063 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000012064 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000012065 return;
12066
12067 // Don't diagnose for value- or type-dependent expressions.
12068 if (E->isTypeDependent() || E->isValueDependent())
12069 return;
12070
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012071 // Check for array bounds violations in cases where the check isn't triggered
12072 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12073 // ArraySubscriptExpr is on the RHS of a variable initialization.
12074 CheckArrayAccess(E);
12075
John McCallacf0ee52010-10-08 02:01:28 +000012076 // This is not the right CC for (e.g.) a variable initialization.
12077 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000012078}
12079
Richard Trieu65724892014-11-15 06:37:39 +000012080/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12081/// Input argument E is a logical expression.
12082void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12083 ::CheckBoolLikeConversion(*this, E, CC);
12084}
12085
Richard Smith9f7df0c2017-06-26 23:19:32 +000012086/// Diagnose when expression is an integer constant expression and its evaluation
12087/// results in integer overflow
12088void Sema::CheckForIntOverflow (Expr *E) {
12089 // Use a work list to deal with nested struct initializers.
12090 SmallVector<Expr *, 2> Exprs(1, E);
12091
12092 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000012093 Expr *OriginalE = Exprs.pop_back_val();
12094 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000012095
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000012096 if (isa<BinaryOperator>(E)) {
12097 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000012098 continue;
12099 }
12100
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000012101 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000012102 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000012103 else if (isa<ObjCBoxedExpr>(OriginalE))
12104 E->EvaluateForOverflow(Context);
12105 else if (auto Call = dyn_cast<CallExpr>(E))
12106 Exprs.append(Call->arg_begin(), Call->arg_end());
12107 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12108 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000012109 } while (!Exprs.empty());
12110}
12111
Richard Smithc406cb72013-01-17 01:17:56 +000012112namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012113
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012114/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000012115/// same object.
12116class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012117 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000012118
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012119 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000012120 /// unsequenced if one is an ancestor or a descendent of the other. When we
12121 /// finish processing an expression with sequencing, such as a comma
12122 /// expression, we fold its tree nodes into its parent, since they are
12123 /// unsequenced with respect to nodes we will visit later.
12124 class SequenceTree {
12125 struct Value {
12126 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12127 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000012128 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000012129 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012130 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000012131
12132 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012133 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000012134 /// to some other region.
12135 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000012136 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012137
Serge Gueltonbe885392019-01-20 21:19:56 +000012138 unsigned Index;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012139
12140 explicit Seq(unsigned N) : Index(N) {}
12141
Richard Smithc406cb72013-01-17 01:17:56 +000012142 public:
Serge Gueltonbe885392019-01-20 21:19:56 +000012143 Seq() : Index(0) {}
Richard Smithc406cb72013-01-17 01:17:56 +000012144 };
12145
12146 SequenceTree() { Values.push_back(Value(0)); }
12147 Seq root() const { return Seq(0); }
12148
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012149 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000012150 /// subset of \p Parent. This sequence of operations is sequenced with
12151 /// respect to other children of \p Parent.
12152 Seq allocate(Seq Parent) {
12153 Values.push_back(Value(Parent.Index));
12154 return Seq(Values.size() - 1);
12155 }
12156
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012157 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000012158 void merge(Seq S) {
12159 Values[S.Index].Merged = true;
12160 }
12161
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012162 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000012163 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12164 /// should have been merged into its parent as appropriate.
12165 bool isUnsequenced(Seq Cur, Seq Old) {
12166 unsigned C = representative(Cur.Index);
12167 unsigned Target = representative(Old.Index);
12168 while (C >= Target) {
12169 if (C == Target)
12170 return true;
12171 C = Values[C].Parent;
12172 }
12173 return false;
12174 }
12175
12176 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012177 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000012178 unsigned representative(unsigned K) {
12179 if (Values[K].Merged)
12180 // Perform path compression as we go.
12181 return Values[K].Parent = representative(Values[K].Parent);
12182 return K;
12183 }
12184 };
12185
12186 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012187 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000012188
12189 /// Different flavors of object usage which we track. We only track the
12190 /// least-sequenced usage of each kind.
12191 enum UsageKind {
12192 /// A read of an object. Multiple unsequenced reads are OK.
12193 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012194
Richard Smithc406cb72013-01-17 01:17:56 +000012195 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000012196 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000012197 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012198
Richard Smithc406cb72013-01-17 01:17:56 +000012199 /// A modification of an object which is not sequenced before the value
12200 /// computation of the expression, such as n++.
12201 UK_ModAsSideEffect,
12202
12203 UK_Count = UK_ModAsSideEffect + 1
12204 };
12205
12206 struct Usage {
Serge Gueltonc1904042019-01-20 23:43:37 +000012207 Expr *Use;
Richard Smithc406cb72013-01-17 01:17:56 +000012208 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012209
Serge Gueltonc1904042019-01-20 23:43:37 +000012210 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000012211 };
12212
12213 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000012214 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012215
Richard Smithc406cb72013-01-17 01:17:56 +000012216 /// Have we issued a diagnostic for this variable already?
Serge Gueltonc1904042019-01-20 23:43:37 +000012217 bool Diagnosed;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012218
Serge Gueltonc1904042019-01-20 23:43:37 +000012219 UsageInfo() : Uses(), Diagnosed(false) {}
Richard Smithc406cb72013-01-17 01:17:56 +000012220 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012221 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000012222
12223 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012224
Richard Smithc406cb72013-01-17 01:17:56 +000012225 /// Sequenced regions within the expression.
12226 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012227
Richard Smithc406cb72013-01-17 01:17:56 +000012228 /// Declaration modifications and references which we have seen.
12229 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012230
Richard Smithc406cb72013-01-17 01:17:56 +000012231 /// The region we are currently within.
12232 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012233
Richard Smithc406cb72013-01-17 01:17:56 +000012234 /// Filled in with declarations which were modified as a side-effect
12235 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012236 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12237
Richard Smithd33f5202013-01-17 23:18:09 +000012238 /// Expressions to check later. We defer checking these to reduce
12239 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012240 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000012241
12242 /// RAII object wrapping the visitation of a sequenced subexpression of an
12243 /// expression. At the end of this process, the side-effects of the evaluation
12244 /// become sequenced with respect to the value computation of the result, so
12245 /// we downgrade any UK_ModAsSideEffect within the evaluation to
12246 /// UK_ModAsValue.
12247 struct SequencedSubexpression {
12248 SequencedSubexpression(SequenceChecker &Self)
12249 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12250 Self.ModAsSideEffect = &ModAsSideEffect;
12251 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012252
Richard Smithc406cb72013-01-17 01:17:56 +000012253 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000012254 for (auto &M : llvm::reverse(ModAsSideEffect)) {
12255 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000012256 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000012257 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12258 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000012259 }
12260 Self.ModAsSideEffect = OldModAsSideEffect;
12261 }
12262
12263 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012264 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012265 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000012266 };
12267
Richard Smith40238f02013-06-20 22:21:56 +000012268 /// RAII object wrapping the visitation of a subexpression which we might
12269 /// choose to evaluate as a constant. If any subexpression is evaluated and
12270 /// found to be non-constant, this allows us to suppress the evaluation of
12271 /// the outer expression.
12272 class EvaluationTracker {
12273 public:
12274 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012275 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000012276 Self.EvalTracker = this;
12277 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012278
Richard Smith40238f02013-06-20 22:21:56 +000012279 ~EvaluationTracker() {
12280 Self.EvalTracker = Prev;
12281 if (Prev)
12282 Prev->EvalOK &= EvalOK;
12283 }
12284
12285 bool evaluate(const Expr *E, bool &Result) {
12286 if (!EvalOK || E->isValueDependent())
12287 return false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012288 EvalOK = E->EvaluateAsBooleanCondition(
12289 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
Richard Smith40238f02013-06-20 22:21:56 +000012290 return EvalOK;
12291 }
12292
12293 private:
12294 SequenceChecker &Self;
12295 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012296 bool EvalOK = true;
12297 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000012298
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012299 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000012300 /// if any.
12301 Object getObject(Expr *E, bool Mod) const {
12302 E = E->IgnoreParenCasts();
12303 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12304 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12305 return getObject(UO->getSubExpr(), Mod);
12306 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12307 if (BO->getOpcode() == BO_Comma)
12308 return getObject(BO->getRHS(), Mod);
12309 if (Mod && BO->isAssignmentOp())
12310 return getObject(BO->getLHS(), Mod);
12311 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12312 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12313 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12314 return ME->getMemberDecl();
12315 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12316 // FIXME: If this is a reference, map through to its value.
12317 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000012318 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000012319 }
12320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012321 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000012322 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12323 Usage &U = UI.Uses[UK];
12324 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12325 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12326 ModAsSideEffect->push_back(std::make_pair(O, U));
12327 U.Use = Ref;
12328 U.Seq = Region;
12329 }
12330 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012331
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012332 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000012333 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12334 bool IsModMod) {
12335 if (UI.Diagnosed)
12336 return;
12337
12338 const Usage &U = UI.Uses[OtherKind];
12339 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12340 return;
12341
12342 Expr *Mod = U.Use;
12343 Expr *ModOrUse = Ref;
12344 if (OtherKind == UK_Use)
12345 std::swap(Mod, ModOrUse);
12346
Richard Smith7d02ca42019-05-06 04:14:01 +000012347 SemaRef.DiagRuntimeBehavior(
12348 Mod->getExprLoc(), {Mod, ModOrUse},
12349 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12350 : diag::warn_unsequenced_mod_use)
12351 << O << SourceRange(ModOrUse->getExprLoc()));
Richard Smithc406cb72013-01-17 01:17:56 +000012352 UI.Diagnosed = true;
12353 }
12354
12355 void notePreUse(Object O, Expr *Use) {
12356 UsageInfo &U = UsageMap[O];
12357 // Uses conflict with other modifications.
12358 checkUsage(O, U, Use, UK_ModAsValue, false);
12359 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012360
Richard Smithc406cb72013-01-17 01:17:56 +000012361 void notePostUse(Object O, Expr *Use) {
12362 UsageInfo &U = UsageMap[O];
12363 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12364 addUsage(U, O, Use, UK_Use);
12365 }
12366
12367 void notePreMod(Object O, Expr *Mod) {
12368 UsageInfo &U = UsageMap[O];
12369 // Modifications conflict with other modifications and with uses.
12370 checkUsage(O, U, Mod, UK_ModAsValue, true);
12371 checkUsage(O, U, Mod, UK_Use, false);
12372 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012373
Richard Smithc406cb72013-01-17 01:17:56 +000012374 void notePostMod(Object O, Expr *Use, UsageKind UK) {
12375 UsageInfo &U = UsageMap[O];
12376 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12377 addUsage(U, O, Use, UK);
12378 }
12379
12380public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012381 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012382 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000012383 Visit(E);
12384 }
12385
12386 void VisitStmt(Stmt *S) {
12387 // Skip all statements which aren't expressions for now.
12388 }
12389
12390 void VisitExpr(Expr *E) {
12391 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000012392 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000012393 }
12394
12395 void VisitCastExpr(CastExpr *E) {
12396 Object O = Object();
12397 if (E->getCastKind() == CK_LValueToRValue)
12398 O = getObject(E->getSubExpr(), false);
12399
12400 if (O)
12401 notePreUse(O, E);
12402 VisitExpr(E);
12403 if (O)
12404 notePostUse(O, E);
12405 }
12406
Nicolas Lesser5610cd82019-01-10 19:03:33 +000012407 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12408 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12409 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12410 SequenceTree::Seq OldRegion = Region;
12411
12412 {
12413 SequencedSubexpression SeqBefore(*this);
12414 Region = BeforeRegion;
12415 Visit(SequencedBefore);
12416 }
12417
12418 Region = AfterRegion;
12419 Visit(SequencedAfter);
12420
12421 Region = OldRegion;
12422
12423 Tree.merge(BeforeRegion);
12424 Tree.merge(AfterRegion);
12425 }
12426
12427 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12428 // C++17 [expr.sub]p1:
12429 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12430 // expression E1 is sequenced before the expression E2.
12431 if (SemaRef.getLangOpts().CPlusPlus17)
12432 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12433 else
12434 Base::VisitStmt(ASE);
12435 }
12436
Richard Smithc406cb72013-01-17 01:17:56 +000012437 void VisitBinComma(BinaryOperator *BO) {
12438 // C++11 [expr.comma]p1:
12439 // Every value computation and side effect associated with the left
12440 // expression is sequenced before every value computation and side
12441 // effect associated with the right expression.
Nicolas Lesser5610cd82019-01-10 19:03:33 +000012442 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
Richard Smithc406cb72013-01-17 01:17:56 +000012443 }
12444
12445 void VisitBinAssign(BinaryOperator *BO) {
12446 // The modification is sequenced after the value computation of the LHS
12447 // and RHS, so check it before inspecting the operands and update the
12448 // map afterwards.
12449 Object O = getObject(BO->getLHS(), true);
12450 if (!O)
12451 return VisitExpr(BO);
12452
12453 notePreMod(O, BO);
12454
12455 // C++11 [expr.ass]p7:
12456 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12457 // only once.
12458 //
12459 // Therefore, for a compound assignment operator, O is considered used
12460 // everywhere except within the evaluation of E1 itself.
12461 if (isa<CompoundAssignOperator>(BO))
12462 notePreUse(O, BO);
12463
12464 Visit(BO->getLHS());
12465
12466 if (isa<CompoundAssignOperator>(BO))
12467 notePostUse(O, BO);
12468
12469 Visit(BO->getRHS());
12470
Richard Smith83e37bee2013-06-26 23:16:51 +000012471 // C++11 [expr.ass]p1:
12472 // the assignment is sequenced [...] before the value computation of the
12473 // assignment expression.
12474 // C11 6.5.16/3 has no such rule.
12475 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12476 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000012477 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012478
Richard Smithc406cb72013-01-17 01:17:56 +000012479 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12480 VisitBinAssign(CAO);
12481 }
12482
12483 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12484 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12485 void VisitUnaryPreIncDec(UnaryOperator *UO) {
12486 Object O = getObject(UO->getSubExpr(), true);
12487 if (!O)
12488 return VisitExpr(UO);
12489
12490 notePreMod(O, UO);
12491 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000012492 // C++11 [expr.pre.incr]p1:
12493 // the expression ++x is equivalent to x+=1
12494 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12495 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000012496 }
12497
12498 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12499 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12500 void VisitUnaryPostIncDec(UnaryOperator *UO) {
12501 Object O = getObject(UO->getSubExpr(), true);
12502 if (!O)
12503 return VisitExpr(UO);
12504
12505 notePreMod(O, UO);
12506 Visit(UO->getSubExpr());
12507 notePostMod(O, UO, UK_ModAsSideEffect);
12508 }
12509
12510 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12511 void VisitBinLOr(BinaryOperator *BO) {
12512 // The side-effects of the LHS of an '&&' are sequenced before the
12513 // value computation of the RHS, and hence before the value computation
12514 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12515 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000012516 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000012517 {
12518 SequencedSubexpression Sequenced(*this);
12519 Visit(BO->getLHS());
12520 }
12521
12522 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012523 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000012524 if (!Result)
12525 Visit(BO->getRHS());
12526 } else {
12527 // Check for unsequenced operations in the RHS, treating it as an
12528 // entirely separate evaluation.
12529 //
12530 // FIXME: If there are operations in the RHS which are unsequenced
12531 // with respect to operations outside the RHS, and those operations
12532 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000012533 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000012534 }
Richard Smithc406cb72013-01-17 01:17:56 +000012535 }
12536 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000012537 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000012538 {
12539 SequencedSubexpression Sequenced(*this);
12540 Visit(BO->getLHS());
12541 }
12542
12543 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012544 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000012545 if (Result)
12546 Visit(BO->getRHS());
12547 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000012548 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000012549 }
Richard Smithc406cb72013-01-17 01:17:56 +000012550 }
12551
12552 // Only visit the condition, unless we can be sure which subexpression will
12553 // be chosen.
12554 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000012555 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000012556 {
12557 SequencedSubexpression Sequenced(*this);
12558 Visit(CO->getCond());
12559 }
Richard Smithc406cb72013-01-17 01:17:56 +000012560
12561 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012562 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000012563 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000012564 else {
Richard Smithd33f5202013-01-17 23:18:09 +000012565 WorkList.push_back(CO->getTrueExpr());
12566 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000012567 }
Richard Smithc406cb72013-01-17 01:17:56 +000012568 }
12569
Richard Smithe3dbfe02013-06-30 10:40:20 +000012570 void VisitCallExpr(CallExpr *CE) {
12571 // C++11 [intro.execution]p15:
12572 // When calling a function [...], every value computation and side effect
12573 // associated with any argument expression, or with the postfix expression
12574 // designating the called function, is sequenced before execution of every
12575 // expression or statement in the body of the function [and thus before
12576 // the value computation of its result].
12577 SequencedSubexpression Sequenced(*this);
12578 Base::VisitCallExpr(CE);
12579
12580 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12581 }
12582
Richard Smithc406cb72013-01-17 01:17:56 +000012583 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000012584 // This is a call, so all subexpressions are sequenced before the result.
12585 SequencedSubexpression Sequenced(*this);
12586
Richard Smithc406cb72013-01-17 01:17:56 +000012587 if (!CCE->isListInitialization())
12588 return VisitExpr(CCE);
12589
12590 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012591 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012592 SequenceTree::Seq Parent = Region;
12593 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12594 E = CCE->arg_end();
12595 I != E; ++I) {
12596 Region = Tree.allocate(Parent);
12597 Elts.push_back(Region);
12598 Visit(*I);
12599 }
12600
12601 // Forget that the initializers are sequenced.
12602 Region = Parent;
12603 for (unsigned I = 0; I < Elts.size(); ++I)
12604 Tree.merge(Elts[I]);
12605 }
12606
12607 void VisitInitListExpr(InitListExpr *ILE) {
12608 if (!SemaRef.getLangOpts().CPlusPlus11)
12609 return VisitExpr(ILE);
12610
12611 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012612 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012613 SequenceTree::Seq Parent = Region;
12614 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12615 Expr *E = ILE->getInit(I);
12616 if (!E) continue;
12617 Region = Tree.allocate(Parent);
12618 Elts.push_back(Region);
12619 Visit(E);
12620 }
12621
12622 // Forget that the initializers are sequenced.
12623 Region = Parent;
12624 for (unsigned I = 0; I < Elts.size(); ++I)
12625 Tree.merge(Elts[I]);
12626 }
12627};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012628
12629} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000012630
12631void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012632 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000012633 WorkList.push_back(E);
12634 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000012635 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000012636 SequenceChecker(*this, Item, WorkList);
12637 }
Richard Smithc406cb72013-01-17 01:17:56 +000012638}
12639
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012640void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12641 bool IsConstexpr) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012642 llvm::SaveAndRestore<bool> ConstantContext(
12643 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
Richard Smithc406cb72013-01-17 01:17:56 +000012644 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000012645 if (!E->isInstantiationDependent())
12646 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012647 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000012648 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012649 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000012650}
12651
John McCall1f425642010-11-11 03:21:53 +000012652void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12653 FieldDecl *BitField,
12654 Expr *Init) {
12655 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12656}
12657
David Majnemer61a5bbf2015-04-07 22:08:51 +000012658static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12659 SourceLocation Loc) {
12660 if (!PType->isVariablyModifiedType())
12661 return;
12662 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12663 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12664 return;
12665 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000012666 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12667 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12668 return;
12669 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000012670 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12671 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12672 return;
12673 }
12674
12675 const ArrayType *AT = S.Context.getAsArrayType(PType);
12676 if (!AT)
12677 return;
12678
12679 if (AT->getSizeModifier() != ArrayType::Star) {
12680 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12681 return;
12682 }
12683
12684 S.Diag(Loc, diag::err_array_star_in_function_definition);
12685}
12686
Mike Stump0c2ec772010-01-21 03:59:47 +000012687/// CheckParmsForFunctionDef - Check that the parameters of the given
12688/// function are appropriate for the definition of a function. This
12689/// takes care of any checks that cannot be performed on the
12690/// declaration itself, e.g., that the types of each of the function
12691/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000012692bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000012693 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012694 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000012695 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012696 // C99 6.7.5.3p4: the parameters in a parameter type list in a
12697 // function declarator that is part of a function definition of
12698 // that function shall not have incomplete type.
12699 //
12700 // This is also C++ [dcl.fct]p6.
12701 if (!Param->isInvalidDecl() &&
12702 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012703 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012704 Param->setInvalidDecl();
12705 HasInvalidParm = true;
12706 }
12707
12708 // C99 6.9.1p5: If the declarator includes a parameter type list, the
12709 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000012710 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000012711 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000012712 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012713 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000012714 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000012715
12716 // C99 6.7.5.3p12:
12717 // If the function declarator is not part of a definition of that
12718 // function, parameters may have incomplete type and may use the [*]
12719 // notation in their sequences of declarator specifiers to specify
12720 // variable length array types.
12721 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000012722 // FIXME: This diagnostic should point the '[*]' if source-location
12723 // information is added for it.
12724 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012725
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012726 // If the parameter is a c++ class type and it has to be destructed in the
12727 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012728 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012729 if (!Param->isInvalidDecl()) {
12730 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12731 if (!ClassDecl->isInvalidDecl() &&
12732 !ClassDecl->hasIrrelevantDestructor() &&
12733 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000012734 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012735 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12736 MarkFunctionReferenced(Param->getLocation(), Destructor);
12737 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000012738 }
12739 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012740 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012741
12742 // Parameters with the pass_object_size attribute only need to be marked
12743 // constant at function definitions. Because we lack information about
12744 // whether we're on a declaration or definition when we're instantiating the
12745 // attribute, we need to check for constness here.
12746 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12747 if (!Param->getType().isConstQualified())
12748 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12749 << Attr->getSpelling() << 1;
Aaron Ballmanc3463f62018-12-05 18:56:57 +000012750
12751 // Check for parameter names shadowing fields from the class.
12752 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12753 // The owning context for the parameter should be the function, but we
12754 // want to see if this function's declaration context is a record.
12755 DeclContext *DC = Param->getDeclContext();
12756 if (DC && DC->isFunctionOrMethod()) {
12757 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12758 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12759 RD, /*DeclIsField*/ false);
12760 }
12761 }
Mike Stump0c2ec772010-01-21 03:59:47 +000012762 }
12763
12764 return HasInvalidParm;
12765}
John McCall2b5c1b22010-08-12 21:44:57 +000012766
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012767/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12768/// or MemberExpr.
12769static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12770 ASTContext &Context) {
12771 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12772 return Context.getDeclAlign(DRE->getDecl());
12773
12774 if (const auto *ME = dyn_cast<MemberExpr>(E))
12775 return Context.getDeclAlign(ME->getMemberDecl());
12776
12777 return TypeAlign;
12778}
12779
John McCall2b5c1b22010-08-12 21:44:57 +000012780/// CheckCastAlign - Implements -Wcast-align, which warns when a
12781/// pointer cast increases the alignment requirements.
12782void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12783 // This is actually a lot of work to potentially be doing on every
12784 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012785 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000012786 return;
12787
12788 // Ignore dependent types.
12789 if (T->isDependentType() || Op->getType()->isDependentType())
12790 return;
12791
12792 // Require that the destination be a pointer type.
12793 const PointerType *DestPtr = T->getAs<PointerType>();
12794 if (!DestPtr) return;
12795
12796 // If the destination has alignment 1, we're done.
12797 QualType DestPointee = DestPtr->getPointeeType();
12798 if (DestPointee->isIncompleteType()) return;
12799 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12800 if (DestAlign.isOne()) return;
12801
12802 // Require that the source be a pointer type.
12803 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12804 if (!SrcPtr) return;
12805 QualType SrcPointee = SrcPtr->getPointeeType();
12806
12807 // Whitelist casts from cv void*. We already implicitly
12808 // whitelisted casts to cv void*, since they have alignment 1.
12809 // Also whitelist casts involving incomplete types, which implicitly
12810 // includes 'void'.
12811 if (SrcPointee->isIncompleteType()) return;
12812
12813 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012814
12815 if (auto *CE = dyn_cast<CastExpr>(Op)) {
12816 if (CE->getCastKind() == CK_ArrayToPointerDecay)
12817 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12818 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12819 if (UO->getOpcode() == UO_AddrOf)
12820 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12821 }
12822
John McCall2b5c1b22010-08-12 21:44:57 +000012823 if (SrcAlign >= DestAlign) return;
12824
12825 Diag(TRange.getBegin(), diag::warn_cast_align)
12826 << Op->getType() << T
12827 << static_cast<unsigned>(SrcAlign.getQuantity())
12828 << static_cast<unsigned>(DestAlign.getQuantity())
12829 << TRange << Op->getSourceRange();
12830}
12831
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012832/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000012833/// array member of a struct.
12834///
12835/// We avoid emitting out-of-bounds access warnings for such arrays as they are
12836/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000012837static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000012838 const NamedDecl *ND) {
12839 if (Size != 1 || !ND) return false;
12840
12841 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12842 if (!FD) return false;
12843
12844 // Don't consider sizes resulting from macro expansions or template argument
12845 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000012846
12847 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012848 while (TInfo) {
12849 TypeLoc TL = TInfo->getTypeLoc();
12850 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000012851 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12852 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012853 TInfo = TDL->getTypeSourceInfo();
12854 continue;
12855 }
David Blaikie6adc78e2013-02-18 22:06:02 +000012856 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12857 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000012858 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12859 return false;
12860 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012861 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000012862 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012863
12864 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000012865 if (!RD) return false;
12866 if (RD->isUnion()) return false;
12867 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12868 if (!CRD->isStandardLayout()) return false;
12869 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012870
Benjamin Kramer8c543672011-08-06 03:04:42 +000012871 // See if this is the last field decl in the record.
12872 const Decl *D = FD;
12873 while ((D = D->getNextDeclInContext()))
12874 if (isa<FieldDecl>(D))
12875 return false;
12876 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000012877}
12878
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012879void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012880 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000012881 bool AllowOnePastEnd, bool IndexNegated) {
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012882 // Already diagnosed by the constant evaluator.
12883 if (isConstantEvaluated())
12884 return;
12885
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012886 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012887 if (IndexExpr->isValueDependent())
12888 return;
12889
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000012890 const Type *EffectiveType =
12891 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012892 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012893 const ConstantArrayType *ArrayTy =
Bruno Riccied414842018-12-20 20:05:11 +000012894 Context.getAsConstantArrayType(BaseExpr->getType());
12895
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012896 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000012897 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000012898
Bruno Riccied414842018-12-20 20:05:11 +000012899 const Type *BaseType = ArrayTy->getElementType().getTypePtr();
Bruno Ricci95550e42019-03-25 21:37:10 +000012900 if (EffectiveType->isDependentType() || BaseType->isDependentType())
12901 return;
Bruno Riccied414842018-12-20 20:05:11 +000012902
Fangrui Song407659a2018-11-30 23:41:18 +000012903 Expr::EvalResult Result;
12904 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000012905 return;
Fangrui Song407659a2018-11-30 23:41:18 +000012906
12907 llvm::APSInt index = Result.Val.getInt();
Richard Smith13f67182011-12-16 19:31:14 +000012908 if (IndexNegated)
12909 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000012910
Craig Topperc3ec1492014-05-26 06:22:03 +000012911 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000012912 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012913 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000012914 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012915 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000012916
Ted Kremeneke4b316c2011-02-23 23:06:04 +000012917 if (index.isUnsigned() || !index.isNegative()) {
Bruno Riccif605e822019-01-08 13:52:54 +000012918 // It is possible that the type of the base expression after
12919 // IgnoreParenCasts is incomplete, even though the type of the base
12920 // expression before IgnoreParenCasts is complete (see PR39746 for an
12921 // example). In this case we have no information about whether the array
12922 // access exceeds the array bounds. However we can still diagnose an array
12923 // access which precedes the array bounds.
12924 if (BaseType->isIncompleteType())
12925 return;
12926
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012927 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000012928 if (!size.isStrictlyPositive())
12929 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012930
Nico Weber7c299802011-09-17 22:59:41 +000012931 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012932 // Make sure we're comparing apples to apples when comparing index to size
12933 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12934 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000012935 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000012936 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012937 if (ptrarith_typesize != array_typesize) {
12938 // There's a cast to a different size type involved
12939 uint64_t ratio = array_typesize / ptrarith_typesize;
12940 // TODO: Be smarter about handling cases where array_typesize is not a
12941 // multiple of ptrarith_typesize
12942 if (ptrarith_typesize * ratio == array_typesize)
12943 size *= llvm::APInt(size.getBitWidth(), ratio);
12944 }
12945 }
12946
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012947 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012948 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012949 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012950 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012951
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012952 // For array subscripting the index must be less than size, but for pointer
12953 // arithmetic also allow the index (offset) to be equal to size since
12954 // computing the next address after the end of the array is legal and
12955 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012956 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000012957 return;
12958
12959 // Also don't warn for arrays of size 1 which are members of some
12960 // structure. These are often used to approximate flexible arrays in C89
12961 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012962 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000012963 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012964
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012965 // Suppress the warning if the subscript expression (as identified by the
12966 // ']' location) and the index expression are both from macro expansions
12967 // within a system header.
12968 if (ASE) {
12969 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12970 ASE->getRBracketLoc());
12971 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012972 SourceLocation IndexLoc =
12973 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
Eli Friedman5ba37d52013-08-22 00:27:10 +000012974 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012975 return;
12976 }
12977 }
12978
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012979 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012980 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012981 DiagID = diag::warn_array_index_exceeds_bounds;
12982
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012983 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012984 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012985 << size.toString(10, true)
12986 << (unsigned)size.getLimitedValue(~0U)
12987 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012988 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012989 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012990 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012991 DiagID = diag::warn_ptr_arith_precedes_bounds;
12992 if (index.isNegative()) index = -index;
12993 }
12994
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012995 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012996 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012997 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000012998 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000012999
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000013000 if (!ND) {
13001 // Try harder to find a NamedDecl to point at in the note.
13002 while (const ArraySubscriptExpr *ASE =
13003 dyn_cast<ArraySubscriptExpr>(BaseExpr))
13004 BaseExpr = ASE->getBase()->IgnoreParenCasts();
13005 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000013006 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000013007 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000013008 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000013009 }
13010
Chandler Carruth1af88f12011-02-17 21:10:52 +000013011 if (ND)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013012 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
David Bolvanskyfd075682019-09-06 16:12:48 +000013013 PDiag(diag::note_array_declared_here)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013014 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000013015}
13016
Ted Kremenekdf26df72011-03-01 18:41:00 +000013017void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013018 int AllowOnePastEnd = 0;
13019 while (expr) {
13020 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000013021 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013022 case Stmt::ArraySubscriptExprClass: {
13023 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000013024 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013025 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000013026 expr = ASE->getBase();
13027 break;
13028 }
13029 case Stmt::MemberExprClass: {
13030 expr = cast<MemberExpr>(expr)->getBase();
13031 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013032 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000013033 case Stmt::OMPArraySectionExprClass: {
13034 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13035 if (ASE->getLowerBound())
13036 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13037 /*ASE=*/nullptr, AllowOnePastEnd > 0);
13038 return;
13039 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000013040 case Stmt::UnaryOperatorClass: {
13041 // Only unwrap the * and & unary operators
13042 const UnaryOperator *UO = cast<UnaryOperator>(expr);
13043 expr = UO->getSubExpr();
13044 switch (UO->getOpcode()) {
13045 case UO_AddrOf:
13046 AllowOnePastEnd++;
13047 break;
13048 case UO_Deref:
13049 AllowOnePastEnd--;
13050 break;
13051 default:
13052 return;
13053 }
13054 break;
13055 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000013056 case Stmt::ConditionalOperatorClass: {
13057 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13058 if (const Expr *lhs = cond->getLHS())
13059 CheckArrayAccess(lhs);
13060 if (const Expr *rhs = cond->getRHS())
13061 CheckArrayAccess(rhs);
13062 return;
13063 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000013064 case Stmt::CXXOperatorCallExprClass: {
13065 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13066 for (const auto *Arg : OCE->arguments())
13067 CheckArrayAccess(Arg);
13068 return;
13069 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000013070 default:
13071 return;
13072 }
Peter Collingbourne91147592011-04-15 00:35:48 +000013073 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000013074}
John McCall31168b02011-06-15 23:02:42 +000013075
13076//===--- CHECK: Objective-C retain cycles ----------------------------------//
13077
13078namespace {
John McCall31168b02011-06-15 23:02:42 +000013079
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013080struct RetainCycleOwner {
13081 VarDecl *Variable = nullptr;
13082 SourceRange Range;
13083 SourceLocation Loc;
13084 bool Indirect = false;
13085
13086 RetainCycleOwner() = default;
13087
13088 void setLocsFrom(Expr *e) {
13089 Loc = e->getExprLoc();
13090 Range = e->getSourceRange();
13091 }
13092};
13093
13094} // namespace
John McCall31168b02011-06-15 23:02:42 +000013095
13096/// Consider whether capturing the given variable can possibly lead to
13097/// a retain cycle.
13098static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000013099 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000013100 // lifetime. In MRR, it's captured strongly if the variable is
13101 // __block and has an appropriate type.
13102 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13103 return false;
13104
13105 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013106 if (ref)
13107 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000013108 return true;
13109}
13110
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013111static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000013112 while (true) {
13113 e = e->IgnoreParens();
13114 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13115 switch (cast->getCastKind()) {
13116 case CK_BitCast:
13117 case CK_LValueBitCast:
13118 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000013119 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000013120 e = cast->getSubExpr();
13121 continue;
13122
John McCall31168b02011-06-15 23:02:42 +000013123 default:
13124 return false;
13125 }
13126 }
13127
13128 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13129 ObjCIvarDecl *ivar = ref->getDecl();
13130 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13131 return false;
13132
13133 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013134 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000013135 return false;
13136
13137 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13138 owner.Indirect = true;
13139 return true;
13140 }
13141
13142 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13143 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13144 if (!var) return false;
13145 return considerVariable(var, ref, owner);
13146 }
13147
John McCall31168b02011-06-15 23:02:42 +000013148 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13149 if (member->isArrow()) return false;
13150
13151 // Don't count this as an indirect ownership.
13152 e = member->getBase();
13153 continue;
13154 }
13155
John McCallfe96e0b2011-11-06 09:01:30 +000013156 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13157 // Only pay attention to pseudo-objects on property references.
13158 ObjCPropertyRefExpr *pre
13159 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13160 ->IgnoreParens());
13161 if (!pre) return false;
13162 if (pre->isImplicitProperty()) return false;
13163 ObjCPropertyDecl *property = pre->getExplicitProperty();
13164 if (!property->isRetaining() &&
13165 !(property->getPropertyIvarDecl() &&
13166 property->getPropertyIvarDecl()->getType()
13167 .getObjCLifetime() == Qualifiers::OCL_Strong))
13168 return false;
13169
13170 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013171 if (pre->isSuperReceiver()) {
13172 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13173 if (!owner.Variable)
13174 return false;
13175 owner.Loc = pre->getLocation();
13176 owner.Range = pre->getSourceRange();
13177 return true;
13178 }
John McCallfe96e0b2011-11-06 09:01:30 +000013179 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13180 ->getSourceExpr());
13181 continue;
13182 }
13183
John McCall31168b02011-06-15 23:02:42 +000013184 // Array ivars?
13185
13186 return false;
13187 }
13188}
13189
13190namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013191
John McCall31168b02011-06-15 23:02:42 +000013192 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000013193 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000013194 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013195 Expr *Capturer = nullptr;
13196 bool VarWillBeReased = false;
13197
13198 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13199 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13200 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000013201
13202 void VisitDeclRefExpr(DeclRefExpr *ref) {
13203 if (ref->getDecl() == Variable && !Capturer)
13204 Capturer = ref;
13205 }
13206
John McCall31168b02011-06-15 23:02:42 +000013207 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13208 if (Capturer) return;
13209 Visit(ref->getBase());
13210 if (Capturer && ref->isFreeIvar())
13211 Capturer = ref;
13212 }
13213
13214 void VisitBlockExpr(BlockExpr *block) {
Fangrui Song6907ce22018-07-30 19:24:48 +000013215 // Look inside nested blocks
John McCall31168b02011-06-15 23:02:42 +000013216 if (block->getBlockDecl()->capturesVariable(Variable))
13217 Visit(block->getBlockDecl()->getBody());
13218 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013219
Fariborz Jahanian0e337542012-08-31 20:04:47 +000013220 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13221 if (Capturer) return;
13222 if (OVE->getSourceExpr())
13223 Visit(OVE->getSourceExpr());
13224 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013225
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000013226 void VisitBinaryOperator(BinaryOperator *BinOp) {
13227 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13228 return;
13229 Expr *LHS = BinOp->getLHS();
13230 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13231 if (DRE->getDecl() != Variable)
13232 return;
13233 if (Expr *RHS = BinOp->getRHS()) {
13234 RHS = RHS->IgnoreParenCasts();
13235 llvm::APSInt Value;
13236 VarWillBeReased =
13237 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13238 }
13239 }
13240 }
John McCall31168b02011-06-15 23:02:42 +000013241 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013242
13243} // namespace
John McCall31168b02011-06-15 23:02:42 +000013244
13245/// Check whether the given argument is a block which captures a
13246/// variable.
13247static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13248 assert(owner.Variable && owner.Loc.isValid());
13249
13250 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000013251
13252 // Look through [^{...} copy] and Block_copy(^{...}).
13253 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13254 Selector Cmd = ME->getSelector();
13255 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13256 e = ME->getInstanceReceiver();
13257 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000013258 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000013259 e = e->IgnoreParenCasts();
13260 }
13261 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13262 if (CE->getNumArgs() == 1) {
13263 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000013264 if (Fn) {
13265 const IdentifierInfo *FnI = Fn->getIdentifier();
13266 if (FnI && FnI->isStr("_Block_copy")) {
13267 e = CE->getArg(0)->IgnoreParenCasts();
13268 }
13269 }
Jordan Rose67e887c2012-09-17 17:54:30 +000013270 }
13271 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013272
John McCall31168b02011-06-15 23:02:42 +000013273 BlockExpr *block = dyn_cast<BlockExpr>(e);
13274 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000013275 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000013276
13277 FindCaptureVisitor visitor(S.Context, owner.Variable);
13278 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000013279 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000013280}
13281
13282static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13283 RetainCycleOwner &owner) {
13284 assert(capturer);
13285 assert(owner.Variable && owner.Loc.isValid());
13286
13287 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13288 << owner.Variable << capturer->getSourceRange();
13289 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13290 << owner.Indirect << owner.Range;
13291}
13292
13293/// Check for a keyword selector that starts with the word 'add' or
13294/// 'set'.
13295static bool isSetterLikeSelector(Selector sel) {
13296 if (sel.isUnarySelector()) return false;
13297
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013298 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000013299 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000013300 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000013301 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000013302 else if (str.startswith("add")) {
13303 // Specially whitelist 'addOperationWithBlock:'.
13304 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13305 return false;
13306 str = str.substr(3);
13307 }
John McCall31168b02011-06-15 23:02:42 +000013308 else
13309 return false;
13310
13311 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000013312 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000013313}
13314
Benjamin Kramer3a743452015-03-09 15:03:32 +000013315static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13316 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013317 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13318 Message->getReceiverInterface(),
13319 NSAPI::ClassId_NSMutableArray);
13320 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013321 return None;
13322 }
13323
13324 Selector Sel = Message->getSelector();
13325
13326 Optional<NSAPI::NSArrayMethodKind> MKOpt =
13327 S.NSAPIObj->getNSArrayMethodKind(Sel);
13328 if (!MKOpt) {
13329 return None;
13330 }
13331
13332 NSAPI::NSArrayMethodKind MK = *MKOpt;
13333
13334 switch (MK) {
13335 case NSAPI::NSMutableArr_addObject:
13336 case NSAPI::NSMutableArr_insertObjectAtIndex:
13337 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13338 return 0;
13339 case NSAPI::NSMutableArr_replaceObjectAtIndex:
13340 return 1;
13341
13342 default:
13343 return None;
13344 }
13345
13346 return None;
13347}
13348
13349static
13350Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13351 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013352 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13353 Message->getReceiverInterface(),
13354 NSAPI::ClassId_NSMutableDictionary);
13355 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013356 return None;
13357 }
13358
13359 Selector Sel = Message->getSelector();
13360
13361 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13362 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13363 if (!MKOpt) {
13364 return None;
13365 }
13366
13367 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13368
13369 switch (MK) {
13370 case NSAPI::NSMutableDict_setObjectForKey:
13371 case NSAPI::NSMutableDict_setValueForKey:
13372 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13373 return 0;
13374
13375 default:
13376 return None;
13377 }
13378
13379 return None;
13380}
13381
13382static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013383 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13384 Message->getReceiverInterface(),
13385 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000013386
Alex Denisov5dfac812015-08-06 04:51:14 +000013387 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13388 Message->getReceiverInterface(),
13389 NSAPI::ClassId_NSMutableOrderedSet);
13390 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013391 return None;
13392 }
13393
13394 Selector Sel = Message->getSelector();
13395
13396 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13397 if (!MKOpt) {
13398 return None;
13399 }
13400
13401 NSAPI::NSSetMethodKind MK = *MKOpt;
13402
13403 switch (MK) {
13404 case NSAPI::NSMutableSet_addObject:
13405 case NSAPI::NSOrderedSet_setObjectAtIndex:
13406 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13407 case NSAPI::NSOrderedSet_insertObjectAtIndex:
13408 return 0;
13409 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13410 return 1;
13411 }
13412
13413 return None;
13414}
13415
13416void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13417 if (!Message->isInstanceMessage()) {
13418 return;
13419 }
13420
13421 Optional<int> ArgOpt;
13422
13423 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13424 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13425 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13426 return;
13427 }
13428
13429 int ArgIndex = *ArgOpt;
13430
Alex Denisove1d882c2015-03-04 17:55:52 +000013431 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13432 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13433 Arg = OE->getSourceExpr()->IgnoreImpCasts();
13434 }
13435
Alex Denisov5dfac812015-08-06 04:51:14 +000013436 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013437 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000013438 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000013439 Diag(Message->getSourceRange().getBegin(),
13440 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000013441 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000013442 }
13443 }
Alex Denisov5dfac812015-08-06 04:51:14 +000013444 } else {
13445 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13446
13447 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13448 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13449 }
13450
13451 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13452 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13453 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13454 ValueDecl *Decl = ReceiverRE->getDecl();
13455 Diag(Message->getSourceRange().getBegin(),
13456 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000013457 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013458 if (!ArgRE->isObjCSelfExpr()) {
13459 Diag(Decl->getLocation(),
13460 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000013461 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013462 }
13463 }
13464 }
13465 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13466 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13467 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13468 ObjCIvarDecl *Decl = IvarRE->getDecl();
13469 Diag(Message->getSourceRange().getBegin(),
13470 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000013471 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013472 Diag(Decl->getLocation(),
13473 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000013474 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000013475 }
Alex Denisove1d882c2015-03-04 17:55:52 +000013476 }
13477 }
13478 }
Alex Denisove1d882c2015-03-04 17:55:52 +000013479}
13480
John McCall31168b02011-06-15 23:02:42 +000013481/// Check a message send to see if it's likely to cause a retain cycle.
13482void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13483 // Only check instance methods whose selector looks like a setter.
13484 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13485 return;
13486
13487 // Try to find a variable that the receiver is strongly owned by.
13488 RetainCycleOwner owner;
13489 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013490 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000013491 return;
13492 } else {
13493 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13494 owner.Variable = getCurMethodDecl()->getSelfDecl();
13495 owner.Loc = msg->getSuperLoc();
13496 owner.Range = msg->getSuperLoc();
13497 }
13498
13499 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000013500 const ObjCMethodDecl *MD = msg->getMethodDecl();
13501 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13502 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13503 // noescape blocks should not be retained by the method.
13504 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13505 continue;
John McCall31168b02011-06-15 23:02:42 +000013506 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000013507 }
13508 }
John McCall31168b02011-06-15 23:02:42 +000013509}
13510
13511/// Check a property assign to see if it's likely to cause a retain cycle.
13512void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13513 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013514 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000013515 return;
13516
13517 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13518 diagnoseRetainCycle(*this, capturer, owner);
13519}
13520
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013521void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13522 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000013523 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013524 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013525
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013526 // Because we don't have an expression for the variable, we have to set the
13527 // location explicitly here.
13528 Owner.Loc = Var->getLocation();
13529 Owner.Range = Var->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +000013530
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013531 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13532 diagnoseRetainCycle(*this, Capturer, Owner);
13533}
13534
Ted Kremenek9304da92012-12-21 08:04:28 +000013535static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13536 Expr *RHS, bool isProperty) {
13537 // Check if RHS is an Objective-C object literal, which also can get
13538 // immediately zapped in a weak reference. Note that we explicitly
13539 // allow ObjCStringLiterals, since those are designed to never really die.
13540 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013541
Ted Kremenek64873352012-12-21 22:46:35 +000013542 // This enum needs to match with the 'select' in
13543 // warn_objc_arc_literal_assign (off-by-1).
13544 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13545 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13546 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013547
13548 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000013549 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000013550 << (isProperty ? 0 : 1)
13551 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013552
13553 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000013554}
13555
Ted Kremenekc1f014a2012-12-21 19:45:30 +000013556static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13557 Qualifiers::ObjCLifetime LT,
13558 Expr *RHS, bool isProperty) {
13559 // Strip off any implicit cast added to get to the one ARC-specific.
13560 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13561 if (cast->getCastKind() == CK_ARCConsumeObject) {
13562 S.Diag(Loc, diag::warn_arc_retained_assign)
13563 << (LT == Qualifiers::OCL_ExplicitNone)
13564 << (isProperty ? 0 : 1)
13565 << RHS->getSourceRange();
13566 return true;
13567 }
13568 RHS = cast->getSubExpr();
13569 }
13570
13571 if (LT == Qualifiers::OCL_Weak &&
13572 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13573 return true;
13574
13575 return false;
13576}
13577
Ted Kremenekb36234d2012-12-21 08:04:20 +000013578bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13579 QualType LHS, Expr *RHS) {
13580 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13581
13582 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13583 return false;
13584
13585 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13586 return true;
13587
13588 return false;
13589}
13590
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013591void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13592 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013593 QualType LHSType;
13594 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000013595 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013596 ObjCPropertyRefExpr *PRE
13597 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13598 if (PRE && !PRE->isImplicitProperty()) {
13599 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13600 if (PD)
13601 LHSType = PD->getType();
13602 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013603
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013604 if (LHSType.isNull())
13605 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000013606
13607 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13608
13609 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013610 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000013611 getCurFunction()->markSafeWeakUse(LHS);
13612 }
13613
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013614 if (checkUnsafeAssigns(Loc, LHSType, RHS))
13615 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000013616
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013617 // FIXME. Check for other life times.
13618 if (LT != Qualifiers::OCL_None)
13619 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013620
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013621 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013622 if (PRE->isImplicitProperty())
13623 return;
13624 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13625 if (!PD)
13626 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013627
Bill Wendling44426052012-12-20 19:22:21 +000013628 unsigned Attributes = PD->getPropertyAttributes();
13629 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013630 // when 'assign' attribute was not explicitly specified
13631 // by user, ignore it and rely on property type itself
13632 // for lifetime info.
13633 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13634 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13635 LHSType->isObjCRetainableType())
13636 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013637
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013638 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000013639 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013640 Diag(Loc, diag::warn_arc_retained_property_assign)
13641 << RHS->getSourceRange();
13642 return;
13643 }
13644 RHS = cast->getSubExpr();
13645 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013646 }
Bill Wendling44426052012-12-20 19:22:21 +000013647 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000013648 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13649 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000013650 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013651 }
13652}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013653
13654//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13655
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013656static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13657 SourceLocation StmtLoc,
13658 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013659 // Do not warn if the body is a macro that expands to nothing, e.g:
13660 //
13661 // #define CALL(x)
13662 // if (condition)
13663 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013664 if (Body->hasLeadingEmptyMacro())
13665 return false;
13666
13667 // Get line numbers of statement and body.
13668 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000013669 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013670 &StmtLineInvalid);
13671 if (StmtLineInvalid)
13672 return false;
13673
13674 bool BodyLineInvalid;
13675 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13676 &BodyLineInvalid);
13677 if (BodyLineInvalid)
13678 return false;
13679
13680 // Warn if null statement and body are on the same line.
13681 if (StmtLine != BodyLine)
13682 return false;
13683
13684 return true;
13685}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013686
13687void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13688 const Stmt *Body,
13689 unsigned DiagID) {
13690 // Since this is a syntactic check, don't emit diagnostic for template
13691 // instantiations, this just adds noise.
13692 if (CurrentInstantiationScope)
13693 return;
13694
13695 // The body should be a null statement.
13696 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13697 if (!NBody)
13698 return;
13699
13700 // Do the usual checks.
13701 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13702 return;
13703
13704 Diag(NBody->getSemiLoc(), DiagID);
13705 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13706}
13707
13708void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13709 const Stmt *PossibleBody) {
13710 assert(!CurrentInstantiationScope); // Ensured by caller
13711
13712 SourceLocation StmtLoc;
13713 const Stmt *Body;
13714 unsigned DiagID;
13715 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13716 StmtLoc = FS->getRParenLoc();
13717 Body = FS->getBody();
13718 DiagID = diag::warn_empty_for_body;
13719 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13720 StmtLoc = WS->getCond()->getSourceRange().getEnd();
13721 Body = WS->getBody();
13722 DiagID = diag::warn_empty_while_body;
13723 } else
13724 return; // Neither `for' nor `while'.
13725
13726 // The body should be a null statement.
13727 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13728 if (!NBody)
13729 return;
13730
13731 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013732 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013733 return;
13734
13735 // Do the usual checks.
13736 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13737 return;
13738
13739 // `for(...);' and `while(...);' are popular idioms, so in order to keep
13740 // noise level low, emit diagnostics only if for/while is followed by a
13741 // CompoundStmt, e.g.:
13742 // for (int i = 0; i < n; i++);
13743 // {
13744 // a(i);
13745 // }
13746 // or if for/while is followed by a statement with more indentation
13747 // than for/while itself:
13748 // for (int i = 0; i < n; i++);
13749 // a(i);
13750 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13751 if (!ProbableTypo) {
13752 bool BodyColInvalid;
13753 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013754 PossibleBody->getBeginLoc(), &BodyColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013755 if (BodyColInvalid)
13756 return;
13757
13758 bool StmtColInvalid;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013759 unsigned StmtCol =
13760 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013761 if (StmtColInvalid)
13762 return;
13763
13764 if (BodyCol > StmtCol)
13765 ProbableTypo = true;
13766 }
13767
13768 if (ProbableTypo) {
13769 Diag(NBody->getSemiLoc(), DiagID);
13770 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13771 }
13772}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013773
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013774//===--- CHECK: Warn on self move with std::move. -------------------------===//
13775
13776/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13777void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13778 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013779 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13780 return;
13781
Richard Smith51ec0cf2017-02-21 01:17:38 +000013782 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013783 return;
13784
13785 // Strip parens and casts away.
13786 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13787 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13788
13789 // Check for a call expression
13790 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13791 if (!CE || CE->getNumArgs() != 1)
13792 return;
13793
13794 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000013795 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013796 return;
13797
13798 // Get argument from std::move
13799 RHSExpr = CE->getArg(0);
13800
13801 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13802 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13803
13804 // Two DeclRefExpr's, check that the decls are the same.
13805 if (LHSDeclRef && RHSDeclRef) {
13806 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13807 return;
13808 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13809 RHSDeclRef->getDecl()->getCanonicalDecl())
13810 return;
13811
13812 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13813 << LHSExpr->getSourceRange()
13814 << RHSExpr->getSourceRange();
13815 return;
13816 }
13817
13818 // Member variables require a different approach to check for self moves.
13819 // MemberExpr's are the same if every nested MemberExpr refers to the same
13820 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13821 // the base Expr's are CXXThisExpr's.
13822 const Expr *LHSBase = LHSExpr;
13823 const Expr *RHSBase = RHSExpr;
13824 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13825 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13826 if (!LHSME || !RHSME)
13827 return;
13828
13829 while (LHSME && RHSME) {
13830 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13831 RHSME->getMemberDecl()->getCanonicalDecl())
13832 return;
13833
13834 LHSBase = LHSME->getBase();
13835 RHSBase = RHSME->getBase();
13836 LHSME = dyn_cast<MemberExpr>(LHSBase);
13837 RHSME = dyn_cast<MemberExpr>(RHSBase);
13838 }
13839
13840 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13841 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13842 if (LHSDeclRef && RHSDeclRef) {
13843 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13844 return;
13845 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13846 RHSDeclRef->getDecl()->getCanonicalDecl())
13847 return;
13848
13849 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13850 << LHSExpr->getSourceRange()
13851 << RHSExpr->getSourceRange();
13852 return;
13853 }
13854
13855 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13856 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13857 << LHSExpr->getSourceRange()
13858 << RHSExpr->getSourceRange();
13859}
13860
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013861//===--- Layout compatibility ----------------------------------------------//
13862
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013863static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013864
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013865/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013866static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013867 // C++11 [dcl.enum] p8:
13868 // Two enumeration types are layout-compatible if they have the same
13869 // underlying type.
13870 return ED1->isComplete() && ED2->isComplete() &&
13871 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13872}
13873
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013874/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013875static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13876 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013877 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13878 return false;
13879
13880 if (Field1->isBitField() != Field2->isBitField())
13881 return false;
13882
13883 if (Field1->isBitField()) {
13884 // Make sure that the bit-fields are the same length.
13885 unsigned Bits1 = Field1->getBitWidthValue(C);
13886 unsigned Bits2 = Field2->getBitWidthValue(C);
13887
13888 if (Bits1 != Bits2)
13889 return false;
13890 }
13891
13892 return true;
13893}
13894
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013895/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013896/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013897static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13898 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013899 // If both records are C++ classes, check that base classes match.
13900 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13901 // If one of records is a CXXRecordDecl we are in C++ mode,
13902 // thus the other one is a CXXRecordDecl, too.
13903 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13904 // Check number of base classes.
13905 if (D1CXX->getNumBases() != D2CXX->getNumBases())
13906 return false;
13907
13908 // Check the base classes.
13909 for (CXXRecordDecl::base_class_const_iterator
13910 Base1 = D1CXX->bases_begin(),
13911 BaseEnd1 = D1CXX->bases_end(),
13912 Base2 = D2CXX->bases_begin();
13913 Base1 != BaseEnd1;
13914 ++Base1, ++Base2) {
13915 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13916 return false;
13917 }
13918 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13919 // If only RD2 is a C++ class, it should have zero base classes.
13920 if (D2CXX->getNumBases() > 0)
13921 return false;
13922 }
13923
13924 // Check the fields.
13925 RecordDecl::field_iterator Field2 = RD2->field_begin(),
13926 Field2End = RD2->field_end(),
13927 Field1 = RD1->field_begin(),
13928 Field1End = RD1->field_end();
13929 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13930 if (!isLayoutCompatible(C, *Field1, *Field2))
13931 return false;
13932 }
13933 if (Field1 != Field1End || Field2 != Field2End)
13934 return false;
13935
13936 return true;
13937}
13938
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013939/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013940/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013941static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13942 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013943 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013944 for (auto *Field2 : RD2->fields())
13945 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013946
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013947 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013948 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13949 I = UnmatchedFields.begin(),
13950 E = UnmatchedFields.end();
13951
13952 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013953 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013954 bool Result = UnmatchedFields.erase(*I);
13955 (void) Result;
13956 assert(Result);
13957 break;
13958 }
13959 }
13960 if (I == E)
13961 return false;
13962 }
13963
13964 return UnmatchedFields.empty();
13965}
13966
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013967static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13968 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013969 if (RD1->isUnion() != RD2->isUnion())
13970 return false;
13971
13972 if (RD1->isUnion())
13973 return isLayoutCompatibleUnion(C, RD1, RD2);
13974 else
13975 return isLayoutCompatibleStruct(C, RD1, RD2);
13976}
13977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013978/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013979static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013980 if (T1.isNull() || T2.isNull())
13981 return false;
13982
13983 // C++11 [basic.types] p11:
13984 // If two types T1 and T2 are the same type, then T1 and T2 are
13985 // layout-compatible types.
13986 if (C.hasSameType(T1, T2))
13987 return true;
13988
13989 T1 = T1.getCanonicalType().getUnqualifiedType();
13990 T2 = T2.getCanonicalType().getUnqualifiedType();
13991
13992 const Type::TypeClass TC1 = T1->getTypeClass();
13993 const Type::TypeClass TC2 = T2->getTypeClass();
13994
13995 if (TC1 != TC2)
13996 return false;
13997
13998 if (TC1 == Type::Enum) {
13999 return isLayoutCompatible(C,
14000 cast<EnumType>(T1)->getDecl(),
14001 cast<EnumType>(T2)->getDecl());
14002 } else if (TC1 == Type::Record) {
14003 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14004 return false;
14005
14006 return isLayoutCompatible(C,
14007 cast<RecordType>(T1)->getDecl(),
14008 cast<RecordType>(T2)->getDecl());
14009 }
14010
14011 return false;
14012}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014013
14014//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14015
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014016/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014017///
14018/// \param TypeExpr Type tag expression, as it appears in user's code.
14019///
14020/// \param VD Declaration of an identifier that appears in a type tag.
14021///
14022/// \param MagicValue Type tag magic value.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014023///
14024/// \param isConstantEvaluated wether the evalaution should be performed in
14025
14026/// constant context.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014027static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014028 const ValueDecl **VD, uint64_t *MagicValue,
14029 bool isConstantEvaluated) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014030 while(true) {
14031 if (!TypeExpr)
14032 return false;
14033
14034 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14035
14036 switch (TypeExpr->getStmtClass()) {
14037 case Stmt::UnaryOperatorClass: {
14038 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14039 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14040 TypeExpr = UO->getSubExpr();
14041 continue;
14042 }
14043 return false;
14044 }
14045
14046 case Stmt::DeclRefExprClass: {
14047 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14048 *VD = DRE->getDecl();
14049 return true;
14050 }
14051
14052 case Stmt::IntegerLiteralClass: {
14053 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14054 llvm::APInt MagicValueAPInt = IL->getValue();
14055 if (MagicValueAPInt.getActiveBits() <= 64) {
14056 *MagicValue = MagicValueAPInt.getZExtValue();
14057 return true;
14058 } else
14059 return false;
14060 }
14061
14062 case Stmt::BinaryConditionalOperatorClass:
14063 case Stmt::ConditionalOperatorClass: {
14064 const AbstractConditionalOperator *ACO =
14065 cast<AbstractConditionalOperator>(TypeExpr);
14066 bool Result;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014067 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14068 isConstantEvaluated)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014069 if (Result)
14070 TypeExpr = ACO->getTrueExpr();
14071 else
14072 TypeExpr = ACO->getFalseExpr();
14073 continue;
14074 }
14075 return false;
14076 }
14077
14078 case Stmt::BinaryOperatorClass: {
14079 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14080 if (BO->getOpcode() == BO_Comma) {
14081 TypeExpr = BO->getRHS();
14082 continue;
14083 }
14084 return false;
14085 }
14086
14087 default:
14088 return false;
14089 }
14090 }
14091}
14092
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014093/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014094///
14095/// \param TypeExpr Expression that specifies a type tag.
14096///
14097/// \param MagicValues Registered magic values.
14098///
14099/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14100/// kind.
14101///
14102/// \param TypeInfo Information about the corresponding C type.
14103///
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014104/// \param isConstantEvaluated wether the evalaution should be performed in
14105/// constant context.
14106///
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014107/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014108static bool GetMatchingCType(
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014109 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14110 const ASTContext &Ctx,
14111 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14112 *MagicValues,
14113 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14114 bool isConstantEvaluated) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014115 FoundWrongKind = false;
14116
14117 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000014118 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014119
14120 uint64_t MagicValue;
14121
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014122 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014123 return false;
14124
14125 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000014126 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014127 if (I->getArgumentKind() != ArgumentKind) {
14128 FoundWrongKind = true;
14129 return false;
14130 }
14131 TypeInfo.Type = I->getMatchingCType();
14132 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14133 TypeInfo.MustBeNull = I->getMustBeNull();
14134 return true;
14135 }
14136 return false;
14137 }
14138
14139 if (!MagicValues)
14140 return false;
14141
14142 llvm::DenseMap<Sema::TypeTagMagicValue,
14143 Sema::TypeTagData>::const_iterator I =
14144 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14145 if (I == MagicValues->end())
14146 return false;
14147
14148 TypeInfo = I->second;
14149 return true;
14150}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014151
14152void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14153 uint64_t MagicValue, QualType Type,
14154 bool LayoutCompatible,
14155 bool MustBeNull) {
14156 if (!TypeTagForDatatypeMagicValues)
14157 TypeTagForDatatypeMagicValues.reset(
14158 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14159
14160 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14161 (*TypeTagForDatatypeMagicValues)[Magic] =
14162 TypeTagData(Type, LayoutCompatible, MustBeNull);
14163}
14164
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014165static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014166 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14167 if (!BT1)
14168 return false;
14169
14170 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14171 if (!BT2)
14172 return false;
14173
14174 BuiltinType::Kind T1Kind = BT1->getKind();
14175 BuiltinType::Kind T2Kind = BT2->getKind();
14176
14177 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
14178 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
14179 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14180 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14181}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014182
14183void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014184 const ArrayRef<const Expr *> ExprArgs,
14185 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014186 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14187 bool IsPointerAttr = Attr->getIsPointer();
14188
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014189 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000014190 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14191 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014192 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000014193 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014194 return;
14195 }
Joel E. Denny81508102018-03-13 14:51:22 +000014196 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014197 bool FoundWrongKind;
14198 TypeTagData TypeInfo;
14199 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014200 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14201 TypeInfo, isConstantEvaluated())) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014202 if (FoundWrongKind)
14203 Diag(TypeTagExpr->getExprLoc(),
14204 diag::warn_type_tag_for_datatype_wrong_kind)
14205 << TypeTagExpr->getSourceRange();
14206 return;
14207 }
14208
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014209 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000014210 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14211 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014212 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000014213 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000014214 return;
14215 }
Joel E. Denny81508102018-03-13 14:51:22 +000014216 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014217 if (IsPointerAttr) {
14218 // Skip implicit cast of pointer to `void *' (as a function argument).
14219 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000014220 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000014221 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014222 ArgumentExpr = ICE->getSubExpr();
14223 }
14224 QualType ArgumentType = ArgumentExpr->getType();
14225
14226 // Passing a `void*' pointer shouldn't trigger a warning.
14227 if (IsPointerAttr && ArgumentType->isVoidPointerType())
14228 return;
14229
14230 if (TypeInfo.MustBeNull) {
14231 // Type tag with matching void type requires a null pointer.
14232 if (!ArgumentExpr->isNullPointerConstant(Context,
14233 Expr::NPC_ValueDependentIsNotNull)) {
14234 Diag(ArgumentExpr->getExprLoc(),
14235 diag::warn_type_safety_null_pointer_required)
14236 << ArgumentKind->getName()
14237 << ArgumentExpr->getSourceRange()
14238 << TypeTagExpr->getSourceRange();
14239 }
14240 return;
14241 }
14242
14243 QualType RequiredType = TypeInfo.Type;
14244 if (IsPointerAttr)
14245 RequiredType = Context.getPointerType(RequiredType);
14246
14247 bool mismatch = false;
14248 if (!TypeInfo.LayoutCompatible) {
14249 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14250
14251 // C++11 [basic.fundamental] p1:
14252 // Plain char, signed char, and unsigned char are three distinct types.
14253 //
14254 // But we treat plain `char' as equivalent to `signed char' or `unsigned
14255 // char' depending on the current char signedness mode.
14256 if (mismatch)
14257 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14258 RequiredType->getPointeeType())) ||
14259 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14260 mismatch = false;
14261 } else
14262 if (IsPointerAttr)
14263 mismatch = !isLayoutCompatible(Context,
14264 ArgumentType->getPointeeType(),
14265 RequiredType->getPointeeType());
14266 else
14267 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14268
14269 if (mismatch)
14270 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000014271 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000014272 << TypeInfo.LayoutCompatible << RequiredType
14273 << ArgumentExpr->getSourceRange()
14274 << TypeTagExpr->getSourceRange();
14275}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014276
14277void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14278 CharUnits Alignment) {
14279 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14280}
14281
14282void Sema::DiagnoseMisalignedMembers() {
14283 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000014284 const NamedDecl *ND = m.RD;
14285 if (ND->getName().empty()) {
14286 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14287 ND = TD;
14288 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014289 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000014290 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014291 }
14292 MisalignedMembers.clear();
14293}
14294
14295void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014296 E = E->IgnoreParens();
14297 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014298 return;
14299 if (isa<UnaryOperator>(E) &&
14300 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14301 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14302 if (isa<MemberExpr>(Op)) {
Fangrui Song75e74e02019-03-31 08:48:19 +000014303 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014304 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014305 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000014306 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14307 Context.getTypeAlignInChars(
14308 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014309 MisalignedMembers.erase(MA);
14310 }
14311 }
14312}
14313
14314void Sema::RefersToMemberWithReducedAlignment(
14315 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000014316 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14317 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014318 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014319 if (!ME)
14320 return;
14321
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000014322 // No need to check expressions with an __unaligned-qualified type.
14323 if (E->getType().getQualifiers().hasUnaligned())
14324 return;
14325
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014326 // For a chain of MemberExpr like "a.b.c.d" this list
14327 // will keep FieldDecl's like [d, c, b].
14328 SmallVector<FieldDecl *, 4> ReverseMemberChain;
14329 const MemberExpr *TopME = nullptr;
14330 bool AnyIsPacked = false;
14331 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014332 QualType BaseType = ME->getBase()->getType();
14333 if (ME->isArrow())
14334 BaseType = BaseType->getPointeeType();
14335 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000014336 if (RD->isInvalidDecl())
14337 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014338
14339 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014340 auto *FD = dyn_cast<FieldDecl>(MD);
14341 // We do not care about non-data members.
14342 if (!FD || FD->isInvalidDecl())
14343 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014344
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014345 AnyIsPacked =
14346 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14347 ReverseMemberChain.push_back(FD);
14348
14349 TopME = ME;
14350 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14351 } while (ME);
14352 assert(TopME && "We did not compute a topmost MemberExpr!");
14353
14354 // Not the scope of this diagnostic.
14355 if (!AnyIsPacked)
14356 return;
14357
14358 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14359 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14360 // TODO: The innermost base of the member expression may be too complicated.
14361 // For now, just disregard these cases. This is left for future
14362 // improvement.
14363 if (!DRE && !isa<CXXThisExpr>(TopBase))
14364 return;
14365
14366 // Alignment expected by the whole expression.
14367 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14368
14369 // No need to do anything else with this case.
14370 if (ExpectedAlignment.isOne())
14371 return;
14372
14373 // Synthesize offset of the whole access.
14374 CharUnits Offset;
14375 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14376 I++) {
14377 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14378 }
14379
14380 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14381 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14382 ReverseMemberChain.back()->getParent()->getTypeForDecl());
14383
14384 // The base expression of the innermost MemberExpr may give
14385 // stronger guarantees than the class containing the member.
14386 if (DRE && !TopME->isArrow()) {
14387 const ValueDecl *VD = DRE->getDecl();
14388 if (!VD->getType()->isReferenceType())
14389 CompleteObjectAlignment =
14390 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14391 }
14392
14393 // Check if the synthesized offset fulfills the alignment.
14394 if (Offset % ExpectedAlignment != 0 ||
14395 // It may fulfill the offset it but the effective alignment may still be
14396 // lower than the expected expression alignment.
14397 CompleteObjectAlignment < ExpectedAlignment) {
14398 // If this happens, we want to determine a sensible culprit of this.
14399 // Intuitively, watching the chain of member expressions from right to
14400 // left, we start with the required alignment (as required by the field
14401 // type) but some packed attribute in that chain has reduced the alignment.
14402 // It may happen that another packed structure increases it again. But if
14403 // we are here such increase has not been enough. So pointing the first
14404 // FieldDecl that either is packed or else its RecordDecl is,
14405 // seems reasonable.
14406 FieldDecl *FD = nullptr;
14407 CharUnits Alignment;
14408 for (FieldDecl *FDI : ReverseMemberChain) {
14409 if (FDI->hasAttr<PackedAttr>() ||
14410 FDI->getParent()->hasAttr<PackedAttr>()) {
14411 FD = FDI;
14412 Alignment = std::min(
14413 Context.getTypeAlignInChars(FD->getType()),
14414 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14415 break;
14416 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014417 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000014418 assert(FD && "We did not find a packed FieldDecl!");
14419 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014420 }
14421}
14422
14423void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14424 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000014425
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000014426 RefersToMemberWithReducedAlignment(
14427 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14428 _2, _3, _4));
14429}