blob: 9fed4761b9b8c404ec6688a13858c59966763479 [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000015#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000017#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000019#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000024#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000029#include "clang/AST/ExprOpenMP.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000030#include "clang/AST/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000031#include "clang/AST/NSAPI.h"
Akira Hatanaka2be04412018-04-17 19:13:41 +000032#include "clang/AST/NonTrivialTypeVisitor.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000033#include "clang/AST/OperationKinds.h"
34#include "clang/AST/Stmt.h"
35#include "clang/AST/TemplateBase.h"
36#include "clang/AST/Type.h"
37#include "clang/AST/TypeLoc.h"
38#include "clang/AST/UnresolvedSet.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000039#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000040#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000041#include "clang/Basic/Diagnostic.h"
42#include "clang/Basic/IdentifierTable.h"
43#include "clang/Basic/LLVM.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/OpenCLOptions.h"
46#include "clang/Basic/OperatorKinds.h"
47#include "clang/Basic/PartialDiagnostic.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000051#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000052#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000053#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000054#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000055#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000056#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000058#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000059#include "clang/Sema/Ownership.h"
60#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000061#include "clang/Sema/ScopeInfo.h"
62#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000063#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000064#include "llvm/ADT/APFloat.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000072#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000073#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000074#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000075#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000076#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/ADT/StringSwitch.h"
79#include "llvm/ADT/Triple.h"
80#include "llvm/Support/AtomicOrdering.h"
81#include "llvm/Support/Casting.h"
82#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000083#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000084#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000085#include "llvm/Support/Format.h"
86#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000087#include "llvm/Support/MathExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000088#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000089#include <algorithm>
90#include <cassert>
91#include <cstddef>
92#include <cstdint>
93#include <functional>
94#include <limits>
95#include <string>
96#include <tuple>
97#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000098
Chris Lattnerb87b1b32007-08-10 20:18:51 +000099using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +0000100using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000101
Chris Lattnera26fb342009-02-18 17:49:48 +0000102SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000106}
107
John McCallbebede42011-02-26 05:39:39 +0000108/// Checks that a call expression's argument count is the desired number.
109/// This is useful when doing custom type-checking. Returns true on error.
110static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111 unsigned argCount = call->getNumArgs();
112 if (argCount == desiredArgCount) return false;
113
114 if (argCount < desiredArgCount)
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
John McCall03107a42015-10-29 20:48:01 +0000194static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195 if (checkArgCount(S, TheCall, 3))
196 return true;
197
198 // First two arguments should be integers.
199 for (unsigned I = 0; I < 2; ++I) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000200 ExprResult Arg = TheCall->getArg(I);
201 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000202 if (!Ty->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000203 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
Erich Keane1d73d1a2018-06-13 13:25:11 +0000204 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000205 return true;
206 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000207 InitializedEntity Entity = InitializedEntity::InitializeParameter(
208 S.getASTContext(), Ty, /*consume*/ false);
209 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
210 if (Arg.isInvalid())
211 return true;
212 TheCall->setArg(I, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000213 }
214
215 // Third argument should be a pointer to a non-const integer.
216 // IRGen correctly handles volatile, restrict, and address spaces, and
217 // the other qualifiers aren't possible.
218 {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000219 ExprResult Arg = TheCall->getArg(2);
220 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000221 const auto *PtrTy = Ty->getAs<PointerType>();
222 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
223 !PtrTy->getPointeeType().isConstQualified())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000224 S.Diag(Arg.get()->getBeginLoc(),
Erich Keane1d73d1a2018-06-13 13:25:11 +0000225 diag::err_overflow_builtin_must_be_ptr_int)
226 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000227 return true;
228 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000229 InitializedEntity Entity = InitializedEntity::InitializeParameter(
230 S.getASTContext(), Ty, /*consume*/ false);
231 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
232 if (Arg.isInvalid())
233 return true;
234 TheCall->setArg(2, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000235 }
John McCall03107a42015-10-29 20:48:01 +0000236 return false;
237}
238
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000239static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Fangrui Song99337e22018-07-20 08:19:20 +0000240 CallExpr *TheCall, unsigned SizeIdx,
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000241 unsigned DstSizeIdx,
242 StringRef LikelyMacroName) {
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000243 if (TheCall->getNumArgs() <= SizeIdx ||
244 TheCall->getNumArgs() <= DstSizeIdx)
245 return;
246
247 const Expr *SizeArg = TheCall->getArg(SizeIdx);
248 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
249
Fangrui Song407659a2018-11-30 23:41:18 +0000250 Expr::EvalResult SizeResult, DstSizeResult;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000251
252 // find out if both sizes are known at compile time
Fangrui Song407659a2018-11-30 23:41:18 +0000253 if (!SizeArg->EvaluateAsInt(SizeResult, S.Context) ||
254 !DstSizeArg->EvaluateAsInt(DstSizeResult, S.Context))
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000255 return;
256
Fangrui Song407659a2018-11-30 23:41:18 +0000257 llvm::APSInt Size = SizeResult.Val.getInt();
258 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
259
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000260 if (Size.ule(DstSize))
261 return;
262
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000263 // Confirmed overflow, so generate the diagnostic.
264 StringRef FunctionName = FDecl->getName();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000265 SourceLocation SL = TheCall->getBeginLoc();
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000266 SourceManager &SM = S.getSourceManager();
267 // If we're in an expansion of a macro whose name corresponds to this builtin,
268 // use the simple macro name and location.
269 if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) ==
270 LikelyMacroName) {
271 FunctionName = LikelyMacroName;
272 SL = SM.getImmediateMacroCallerLoc(SL);
273 }
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000274
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000275 S.Diag(SL, diag::warn_memcpy_chk_overflow)
276 << FunctionName << DstSize.toString(/*Radix=*/10)
277 << Size.toString(/*Radix=*/10);
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000278}
279
Peter Collingbournef7706832014-12-12 23:41:25 +0000280static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
281 if (checkArgCount(S, BuiltinCall, 2))
282 return true;
283
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000284 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
Peter Collingbournef7706832014-12-12 23:41:25 +0000285 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
286 Expr *Call = BuiltinCall->getArg(0);
287 Expr *Chain = BuiltinCall->getArg(1);
288
289 if (Call->getStmtClass() != Stmt::CallExprClass) {
290 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
291 << Call->getSourceRange();
292 return true;
293 }
294
295 auto CE = cast<CallExpr>(Call);
296 if (CE->getCallee()->getType()->isBlockPointerType()) {
297 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
298 << Call->getSourceRange();
299 return true;
300 }
301
302 const Decl *TargetDecl = CE->getCalleeDecl();
303 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
304 if (FD->getBuiltinID()) {
305 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
306 << Call->getSourceRange();
307 return true;
308 }
309
310 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
311 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
312 << Call->getSourceRange();
313 return true;
314 }
315
316 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
317 if (ChainResult.isInvalid())
318 return true;
319 if (!ChainResult.get()->getType()->isPointerType()) {
320 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
321 << Chain->getSourceRange();
322 return true;
323 }
324
David Majnemerced8bdf2015-02-25 17:36:15 +0000325 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000326 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
327 QualType BuiltinTy = S.Context.getFunctionType(
328 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
329 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
330
331 Builtin =
332 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
333
334 BuiltinCall->setType(CE->getType());
335 BuiltinCall->setValueKind(CE->getValueKind());
336 BuiltinCall->setObjectKind(CE->getObjectKind());
337 BuiltinCall->setCallee(Builtin);
338 BuiltinCall->setArg(1, ChainResult.get());
339
340 return false;
341}
342
Reid Kleckner1d59f992015-01-22 01:36:17 +0000343static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
344 Scope::ScopeFlags NeededScopeFlags,
345 unsigned DiagID) {
346 // Scopes aren't available during instantiation. Fortunately, builtin
347 // functions cannot be template args so they cannot be formed through template
348 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000349 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000350 return false;
351
352 Scope *S = SemaRef.getCurScope();
353 while (S && !S->isSEHExceptScope())
354 S = S->getParent();
355 if (!S || !(S->getFlags() & NeededScopeFlags)) {
356 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
357 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
358 << DRE->getDecl()->getIdentifier();
359 return true;
360 }
361
362 return false;
363}
364
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000365static inline bool isBlockPointer(Expr *Arg) {
366 return Arg->getType()->isBlockPointerType();
367}
368
369/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
370/// void*, which is a requirement of device side enqueue.
371static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
372 const BlockPointerType *BPT =
373 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
374 ArrayRef<QualType> Params =
375 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
376 unsigned ArgCounter = 0;
377 bool IllegalParams = false;
378 // Iterate through the block parameters until either one is found that is not
379 // a local void*, or the block is valid.
380 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
381 I != E; ++I, ++ArgCounter) {
382 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
383 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
384 LangAS::opencl_local) {
385 // Get the location of the error. If a block literal has been passed
386 // (BlockExpr) then we can point straight to the offending argument,
387 // else we just point to the variable reference.
388 SourceLocation ErrorLoc;
389 if (isa<BlockExpr>(BlockArg)) {
390 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000391 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000392 } else if (isa<DeclRefExpr>(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000393 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000394 }
395 S.Diag(ErrorLoc,
396 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
397 IllegalParams = true;
398 }
399 }
400
401 return IllegalParams;
402}
403
Joey Gouly84ae3362017-07-31 15:15:59 +0000404static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
405 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000406 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
407 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
Joey Gouly84ae3362017-07-31 15:15:59 +0000408 return true;
409 }
410 return false;
411}
412
Joey Goulyfa76b492017-08-01 13:27:09 +0000413static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
414 if (checkArgCount(S, TheCall, 2))
415 return true;
416
417 if (checkOpenCLSubgroupExt(S, TheCall))
418 return true;
419
420 // First argument is an ndrange_t type.
421 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000422 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000423 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000424 << TheCall->getDirectCallee() << "'ndrange_t'";
425 return true;
426 }
427
428 Expr *BlockArg = TheCall->getArg(1);
429 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000430 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000431 << TheCall->getDirectCallee() << "block";
432 return true;
433 }
434 return checkOpenCLBlockArgs(S, BlockArg);
435}
436
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000437/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
438/// get_kernel_work_group_size
439/// and get_kernel_preferred_work_group_size_multiple builtin functions.
440static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
441 if (checkArgCount(S, TheCall, 1))
442 return true;
443
444 Expr *BlockArg = TheCall->getArg(0);
445 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000446 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000447 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000448 return true;
449 }
450 return checkOpenCLBlockArgs(S, BlockArg);
451}
452
Simon Pilgrim2c518802017-03-30 14:13:19 +0000453/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000454static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
455 const QualType &IntType);
456
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000457static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000458 unsigned Start, unsigned End) {
459 bool IllegalParams = false;
460 for (unsigned I = Start; I <= End; ++I)
461 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
462 S.Context.getSizeType());
463 return IllegalParams;
464}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000465
466/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
467/// 'local void*' parameter of passed block.
468static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
469 Expr *BlockArg,
470 unsigned NumNonVarArgs) {
471 const BlockPointerType *BPT =
472 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
473 unsigned NumBlockParams =
474 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
475 unsigned TotalNumArgs = TheCall->getNumArgs();
476
477 // For each argument passed to the block, a corresponding uint needs to
478 // be passed to describe the size of the local memory.
479 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000480 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000481 diag::err_opencl_enqueue_kernel_local_size_args);
482 return true;
483 }
484
485 // Check that the sizes of the local memory are specified by integers.
486 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
487 TotalNumArgs - 1);
488}
489
490/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
491/// overload formats specified in Table 6.13.17.1.
492/// int enqueue_kernel(queue_t queue,
493/// kernel_enqueue_flags_t flags,
494/// const ndrange_t ndrange,
495/// void (^block)(void))
496/// int enqueue_kernel(queue_t queue,
497/// kernel_enqueue_flags_t flags,
498/// const ndrange_t ndrange,
499/// uint num_events_in_wait_list,
500/// clk_event_t *event_wait_list,
501/// clk_event_t *event_ret,
502/// void (^block)(void))
503/// int enqueue_kernel(queue_t queue,
504/// kernel_enqueue_flags_t flags,
505/// const ndrange_t ndrange,
506/// void (^block)(local void*, ...),
507/// uint size0, ...)
508/// int enqueue_kernel(queue_t queue,
509/// kernel_enqueue_flags_t flags,
510/// const ndrange_t ndrange,
511/// uint num_events_in_wait_list,
512/// clk_event_t *event_wait_list,
513/// clk_event_t *event_ret,
514/// void (^block)(local void*, ...),
515/// uint size0, ...)
516static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
517 unsigned NumArgs = TheCall->getNumArgs();
518
519 if (NumArgs < 4) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000520 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000521 return true;
522 }
523
524 Expr *Arg0 = TheCall->getArg(0);
525 Expr *Arg1 = TheCall->getArg(1);
526 Expr *Arg2 = TheCall->getArg(2);
527 Expr *Arg3 = TheCall->getArg(3);
528
529 // First argument always needs to be a queue_t type.
530 if (!Arg0->getType()->isQueueT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000531 S.Diag(TheCall->getArg(0)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000532 diag::err_opencl_builtin_expected_type)
533 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000534 return true;
535 }
536
537 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
538 if (!Arg1->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000539 S.Diag(TheCall->getArg(1)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000540 diag::err_opencl_builtin_expected_type)
541 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000542 return true;
543 }
544
545 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000546 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000547 S.Diag(TheCall->getArg(2)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000548 diag::err_opencl_builtin_expected_type)
549 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000550 return true;
551 }
552
553 // With four arguments, there is only one form that the function could be
554 // called in: no events and no variable arguments.
555 if (NumArgs == 4) {
556 // check that the last argument is the right block type.
557 if (!isBlockPointer(Arg3)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000558 S.Diag(Arg3->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 // we have a block type, check the prototype
563 const BlockPointerType *BPT =
564 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
565 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000566 S.Diag(Arg3->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000567 diag::err_opencl_enqueue_kernel_blocks_no_args);
568 return true;
569 }
570 return false;
571 }
572 // we can have block + varargs.
573 if (isBlockPointer(Arg3))
574 return (checkOpenCLBlockArgs(S, Arg3) ||
575 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
576 // last two cases with either exactly 7 args or 7 args and varargs.
577 if (NumArgs >= 7) {
578 // check common block argument.
579 Expr *Arg6 = TheCall->getArg(6);
580 if (!isBlockPointer(Arg6)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000581 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000582 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000583 return true;
584 }
585 if (checkOpenCLBlockArgs(S, Arg6))
586 return true;
587
588 // Forth argument has to be any integer type.
589 if (!Arg3->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000590 S.Diag(TheCall->getArg(3)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000591 diag::err_opencl_builtin_expected_type)
592 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000593 return true;
594 }
595 // check remaining common arguments.
596 Expr *Arg4 = TheCall->getArg(4);
597 Expr *Arg5 = TheCall->getArg(5);
598
Anastasia Stulova2b461202016-11-14 15:34:01 +0000599 // Fifth argument is always passed as a pointer to clk_event_t.
600 if (!Arg4->isNullPointerConstant(S.Context,
601 Expr::NPC_ValueDependentIsNotNull) &&
602 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000603 S.Diag(TheCall->getArg(4)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000604 diag::err_opencl_builtin_expected_type)
605 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000606 << S.Context.getPointerType(S.Context.OCLClkEventTy);
607 return true;
608 }
609
Anastasia Stulova2b461202016-11-14 15:34:01 +0000610 // Sixth argument is always passed as a pointer to clk_event_t.
611 if (!Arg5->isNullPointerConstant(S.Context,
612 Expr::NPC_ValueDependentIsNotNull) &&
613 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000614 Arg5->getType()->getPointeeType()->isClkEventT())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000615 S.Diag(TheCall->getArg(5)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000616 diag::err_opencl_builtin_expected_type)
617 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000618 << S.Context.getPointerType(S.Context.OCLClkEventTy);
619 return true;
620 }
621
622 if (NumArgs == 7)
623 return false;
624
625 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
626 }
627
628 // None of the specific case has been detected, give generic error
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000629 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000630 diag::err_opencl_enqueue_kernel_incorrect_args);
631 return true;
632}
633
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000634/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000635static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000636 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000637}
638
639/// Returns true if pipe element type is different from the pointer.
640static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
641 const Expr *Arg0 = Call->getArg(0);
642 // First argument type should always be pipe.
643 if (!Arg0->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000644 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000645 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000646 return true;
647 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000648 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000649 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
650 // Validates the access qualifier is compatible with the call.
651 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
652 // read_only and write_only, and assumed to be read_only if no qualifier is
653 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000654 switch (Call->getDirectCallee()->getBuiltinID()) {
655 case Builtin::BIread_pipe:
656 case Builtin::BIreserve_read_pipe:
657 case Builtin::BIcommit_read_pipe:
658 case Builtin::BIwork_group_reserve_read_pipe:
659 case Builtin::BIsub_group_reserve_read_pipe:
660 case Builtin::BIwork_group_commit_read_pipe:
661 case Builtin::BIsub_group_commit_read_pipe:
662 if (!(!AccessQual || AccessQual->isReadOnly())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000663 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000664 diag::err_opencl_builtin_pipe_invalid_access_modifier)
665 << "read_only" << Arg0->getSourceRange();
666 return true;
667 }
668 break;
669 case Builtin::BIwrite_pipe:
670 case Builtin::BIreserve_write_pipe:
671 case Builtin::BIcommit_write_pipe:
672 case Builtin::BIwork_group_reserve_write_pipe:
673 case Builtin::BIsub_group_reserve_write_pipe:
674 case Builtin::BIwork_group_commit_write_pipe:
675 case Builtin::BIsub_group_commit_write_pipe:
676 if (!(AccessQual && AccessQual->isWriteOnly())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000677 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000678 diag::err_opencl_builtin_pipe_invalid_access_modifier)
679 << "write_only" << Arg0->getSourceRange();
680 return true;
681 }
682 break;
683 default:
684 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000685 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000686 return false;
687}
688
689/// Returns true if pipe element type is different from the pointer.
690static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
691 const Expr *Arg0 = Call->getArg(0);
692 const Expr *ArgIdx = Call->getArg(Idx);
693 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000694 const QualType EltTy = PipeTy->getElementType();
695 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000696 // The Idx argument should be a pointer and the type of the pointer and
697 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000698 if (!ArgTy ||
699 !S.Context.hasSameType(
700 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000701 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000702 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000703 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000704 return true;
705 }
706 return false;
707}
708
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000709// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000710// \param S Reference to the semantic analyzer.
711// \param Call A pointer to the builtin call.
712// \return True if a semantic error has been found, false otherwise.
713static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000714 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
715 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000716 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000717 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000718 if (checkOpenCLPipeArg(S, Call))
719 return true;
720 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000721 // read/write_pipe(pipe T, T*).
722 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000723 if (checkOpenCLPipePacketType(S, Call, 1))
724 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000725 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000726
727 case 4: {
728 if (checkOpenCLPipeArg(S, Call))
729 return true;
730 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000731 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
732 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000733 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000734 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000735 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000736 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000737 return true;
738 }
739
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000740 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000741 const Expr *Arg2 = Call->getArg(2);
742 if (!Arg2->getType()->isIntegerType() &&
743 !Arg2->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000744 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000745 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000746 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000747 return true;
748 }
749
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000750 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000751 if (checkOpenCLPipePacketType(S, Call, 3))
752 return true;
753 } break;
754 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000755 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000756 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000757 return true;
758 }
759
760 return false;
761}
762
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000763// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000764// /_}reserve_{read/write}_pipe
765// \param S Reference to the semantic analyzer.
766// \param Call The call to the builtin function to be analyzed.
767// \return True if a semantic error was found, false otherwise.
768static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
769 if (checkArgCount(S, Call, 2))
770 return true;
771
772 if (checkOpenCLPipeArg(S, Call))
773 return true;
774
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000775 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000776 if (!Call->getArg(1)->getType()->isIntegerType() &&
777 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000778 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000779 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000780 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000781 return true;
782 }
783
Joey Gouly922ca232017-08-09 14:52:47 +0000784 // Since return type of reserve_read/write_pipe built-in function is
Aaron Ballman68d50642018-06-19 14:53:20 +0000785 // reserve_id_t, which is not defined in the builtin def file , we used int
786 // as return type and need to override the return type of these functions.
787 Call->setType(S.Context.OCLReserveIDTy);
788
789 return false;
790}
791
792// Performs a semantic analysis on {work_group_/sub_group_
793// /_}commit_{read/write}_pipe
794// \param S Reference to the semantic analyzer.
795// \param Call The call to the builtin function to be analyzed.
796// \return True if a semantic error was found, false otherwise.
797static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
798 if (checkArgCount(S, Call, 2))
799 return true;
800
801 if (checkOpenCLPipeArg(S, Call))
802 return true;
803
804 // Check reserve_id_t.
805 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000806 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000807 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
808 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
809 return true;
810 }
811
812 return false;
813}
814
815// Performs a semantic analysis on the call to built-in Pipe
816// Query Functions.
817// \param S Reference to the semantic analyzer.
818// \param Call The call to the builtin function to be analyzed.
819// \return True if a semantic error was found, false otherwise.
820static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
821 if (checkArgCount(S, Call, 1))
822 return true;
823
824 if (!Call->getArg(0)->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000825 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000826 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
827 return true;
828 }
829
830 return false;
831}
832
833// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
834// Performs semantic analysis for the to_global/local/private call.
835// \param S Reference to the semantic analyzer.
836// \param BuiltinID ID of the builtin function.
837// \param Call A pointer to the builtin call.
838// \return True if a semantic error has been found, false otherwise.
839static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
840 CallExpr *Call) {
841 if (Call->getNumArgs() != 1) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000842 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
Aaron Ballman68d50642018-06-19 14:53:20 +0000843 << Call->getDirectCallee() << Call->getSourceRange();
844 return true;
845 }
846
847 auto RT = Call->getArg(0)->getType();
848 if (!RT->isPointerType() || RT->getPointeeType()
849 .getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000850 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000851 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
852 return true;
853 }
854
Sven van Haastregt1076cc22018-09-20 10:07:27 +0000855 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
856 S.Diag(Call->getArg(0)->getBeginLoc(),
857 diag::warn_opencl_generic_address_space_arg)
858 << Call->getDirectCallee()->getNameInfo().getAsString()
859 << Call->getArg(0)->getSourceRange();
860 }
861
Aaron Ballman68d50642018-06-19 14:53:20 +0000862 RT = RT->getPointeeType();
863 auto Qual = RT.getQualifiers();
864 switch (BuiltinID) {
865 case Builtin::BIto_global:
866 Qual.setAddressSpace(LangAS::opencl_global);
867 break;
868 case Builtin::BIto_local:
869 Qual.setAddressSpace(LangAS::opencl_local);
870 break;
871 case Builtin::BIto_private:
872 Qual.setAddressSpace(LangAS::opencl_private);
873 break;
874 default:
875 llvm_unreachable("Invalid builtin function");
876 }
877 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
878 RT.getUnqualifiedType(), Qual)));
879
880 return false;
881}
882
883// Emit an error and return true if the current architecture is not in the list
884// of supported architectures.
885static bool
886CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
887 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
888 llvm::Triple::ArchType CurArch =
889 S.getASTContext().getTargetInfo().getTriple().getArch();
890 if (llvm::is_contained(SupportedArchs, CurArch))
891 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000892 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
Aaron Ballman68d50642018-06-19 14:53:20 +0000893 << TheCall->getSourceRange();
894 return true;
895}
896
897ExprResult
898Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
899 CallExpr *TheCall) {
900 ExprResult TheCallResult(TheCall);
901
902 // Find out if any arguments are required to be integer constant expressions.
903 unsigned ICEArguments = 0;
904 ASTContext::GetBuiltinTypeError Error;
905 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
906 if (Error != ASTContext::GE_None)
907 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
Fangrui Song6907ce22018-07-30 19:24:48 +0000908
Aaron Ballman68d50642018-06-19 14:53:20 +0000909 // If any arguments are required to be ICE's, check and diagnose.
910 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
911 // Skip arguments not required to be ICE's.
912 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000913
Aaron Ballman68d50642018-06-19 14:53:20 +0000914 llvm::APSInt Result;
915 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
916 return true;
917 ICEArguments &= ~(1 << ArgNo);
918 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000919
Aaron Ballman68d50642018-06-19 14:53:20 +0000920 switch (BuiltinID) {
921 case Builtin::BI__builtin___CFStringMakeConstantString:
922 assert(TheCall->getNumArgs() == 1 &&
923 "Wrong # arguments to builtin CFStringMakeConstantString");
924 if (CheckObjCString(TheCall->getArg(0)))
925 return ExprError();
926 break;
927 case Builtin::BI__builtin_ms_va_start:
928 case Builtin::BI__builtin_stdarg_start:
929 case Builtin::BI__builtin_va_start:
930 if (SemaBuiltinVAStart(BuiltinID, TheCall))
931 return ExprError();
932 break;
933 case Builtin::BI__va_start: {
934 switch (Context.getTargetInfo().getTriple().getArch()) {
Martin Storsjo0b339e42018-09-27 08:24:15 +0000935 case llvm::Triple::aarch64:
Aaron Ballman68d50642018-06-19 14:53:20 +0000936 case llvm::Triple::arm:
937 case llvm::Triple::thumb:
938 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
939 return ExprError();
940 break;
941 default:
942 if (SemaBuiltinVAStart(BuiltinID, TheCall))
943 return ExprError();
944 break;
945 }
946 break;
947 }
948
949 // The acquire, release, and no fence variants are ARM and AArch64 only.
950 case Builtin::BI_interlockedbittestandset_acq:
951 case Builtin::BI_interlockedbittestandset_rel:
952 case Builtin::BI_interlockedbittestandset_nf:
953 case Builtin::BI_interlockedbittestandreset_acq:
954 case Builtin::BI_interlockedbittestandreset_rel:
955 case Builtin::BI_interlockedbittestandreset_nf:
956 if (CheckBuiltinTargetSupport(
957 *this, BuiltinID, TheCall,
958 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
959 return ExprError();
960 break;
961
962 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
963 case Builtin::BI_bittest64:
964 case Builtin::BI_bittestandcomplement64:
965 case Builtin::BI_bittestandreset64:
966 case Builtin::BI_bittestandset64:
967 case Builtin::BI_interlockedbittestandreset64:
968 case Builtin::BI_interlockedbittestandset64:
969 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
970 {llvm::Triple::x86_64, llvm::Triple::arm,
971 llvm::Triple::thumb, llvm::Triple::aarch64}))
972 return ExprError();
973 break;
974
975 case Builtin::BI__builtin_isgreater:
976 case Builtin::BI__builtin_isgreaterequal:
977 case Builtin::BI__builtin_isless:
978 case Builtin::BI__builtin_islessequal:
979 case Builtin::BI__builtin_islessgreater:
980 case Builtin::BI__builtin_isunordered:
981 if (SemaBuiltinUnorderedCompare(TheCall))
982 return ExprError();
983 break;
984 case Builtin::BI__builtin_fpclassify:
985 if (SemaBuiltinFPClassification(TheCall, 6))
986 return ExprError();
987 break;
988 case Builtin::BI__builtin_isfinite:
989 case Builtin::BI__builtin_isinf:
990 case Builtin::BI__builtin_isinf_sign:
991 case Builtin::BI__builtin_isnan:
992 case Builtin::BI__builtin_isnormal:
Aaron Ballmandd0e2b02018-06-19 14:59:11 +0000993 case Builtin::BI__builtin_signbit:
994 case Builtin::BI__builtin_signbitf:
995 case Builtin::BI__builtin_signbitl:
Aaron Ballman68d50642018-06-19 14:53:20 +0000996 if (SemaBuiltinFPClassification(TheCall, 1))
997 return ExprError();
998 break;
999 case Builtin::BI__builtin_shufflevector:
1000 return SemaBuiltinShuffleVector(TheCall);
1001 // TheCall will be freed by the smart pointer here, but that's fine, since
1002 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1003 case Builtin::BI__builtin_prefetch:
1004 if (SemaBuiltinPrefetch(TheCall))
1005 return ExprError();
1006 break;
1007 case Builtin::BI__builtin_alloca_with_align:
1008 if (SemaBuiltinAllocaWithAlign(TheCall))
1009 return ExprError();
1010 break;
1011 case Builtin::BI__assume:
1012 case Builtin::BI__builtin_assume:
1013 if (SemaBuiltinAssume(TheCall))
1014 return ExprError();
1015 break;
1016 case Builtin::BI__builtin_assume_aligned:
1017 if (SemaBuiltinAssumeAligned(TheCall))
1018 return ExprError();
1019 break;
1020 case Builtin::BI__builtin_object_size:
1021 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1022 return ExprError();
1023 break;
1024 case Builtin::BI__builtin_longjmp:
1025 if (SemaBuiltinLongjmp(TheCall))
1026 return ExprError();
1027 break;
1028 case Builtin::BI__builtin_setjmp:
1029 if (SemaBuiltinSetjmp(TheCall))
1030 return ExprError();
1031 break;
1032 case Builtin::BI_setjmp:
1033 case Builtin::BI_setjmpex:
1034 if (checkArgCount(*this, TheCall, 1))
1035 return true;
1036 break;
1037 case Builtin::BI__builtin_classify_type:
1038 if (checkArgCount(*this, TheCall, 1)) return true;
1039 TheCall->setType(Context.IntTy);
1040 break;
1041 case Builtin::BI__builtin_constant_p:
1042 if (checkArgCount(*this, TheCall, 1)) return true;
1043 TheCall->setType(Context.IntTy);
1044 break;
1045 case Builtin::BI__sync_fetch_and_add:
1046 case Builtin::BI__sync_fetch_and_add_1:
1047 case Builtin::BI__sync_fetch_and_add_2:
1048 case Builtin::BI__sync_fetch_and_add_4:
1049 case Builtin::BI__sync_fetch_and_add_8:
1050 case Builtin::BI__sync_fetch_and_add_16:
1051 case Builtin::BI__sync_fetch_and_sub:
1052 case Builtin::BI__sync_fetch_and_sub_1:
1053 case Builtin::BI__sync_fetch_and_sub_2:
1054 case Builtin::BI__sync_fetch_and_sub_4:
1055 case Builtin::BI__sync_fetch_and_sub_8:
1056 case Builtin::BI__sync_fetch_and_sub_16:
1057 case Builtin::BI__sync_fetch_and_or:
1058 case Builtin::BI__sync_fetch_and_or_1:
1059 case Builtin::BI__sync_fetch_and_or_2:
1060 case Builtin::BI__sync_fetch_and_or_4:
1061 case Builtin::BI__sync_fetch_and_or_8:
1062 case Builtin::BI__sync_fetch_and_or_16:
1063 case Builtin::BI__sync_fetch_and_and:
1064 case Builtin::BI__sync_fetch_and_and_1:
1065 case Builtin::BI__sync_fetch_and_and_2:
1066 case Builtin::BI__sync_fetch_and_and_4:
1067 case Builtin::BI__sync_fetch_and_and_8:
1068 case Builtin::BI__sync_fetch_and_and_16:
1069 case Builtin::BI__sync_fetch_and_xor:
1070 case Builtin::BI__sync_fetch_and_xor_1:
1071 case Builtin::BI__sync_fetch_and_xor_2:
1072 case Builtin::BI__sync_fetch_and_xor_4:
1073 case Builtin::BI__sync_fetch_and_xor_8:
1074 case Builtin::BI__sync_fetch_and_xor_16:
1075 case Builtin::BI__sync_fetch_and_nand:
1076 case Builtin::BI__sync_fetch_and_nand_1:
1077 case Builtin::BI__sync_fetch_and_nand_2:
1078 case Builtin::BI__sync_fetch_and_nand_4:
1079 case Builtin::BI__sync_fetch_and_nand_8:
1080 case Builtin::BI__sync_fetch_and_nand_16:
1081 case Builtin::BI__sync_add_and_fetch:
1082 case Builtin::BI__sync_add_and_fetch_1:
1083 case Builtin::BI__sync_add_and_fetch_2:
1084 case Builtin::BI__sync_add_and_fetch_4:
1085 case Builtin::BI__sync_add_and_fetch_8:
1086 case Builtin::BI__sync_add_and_fetch_16:
1087 case Builtin::BI__sync_sub_and_fetch:
1088 case Builtin::BI__sync_sub_and_fetch_1:
1089 case Builtin::BI__sync_sub_and_fetch_2:
1090 case Builtin::BI__sync_sub_and_fetch_4:
1091 case Builtin::BI__sync_sub_and_fetch_8:
1092 case Builtin::BI__sync_sub_and_fetch_16:
1093 case Builtin::BI__sync_and_and_fetch:
1094 case Builtin::BI__sync_and_and_fetch_1:
1095 case Builtin::BI__sync_and_and_fetch_2:
1096 case Builtin::BI__sync_and_and_fetch_4:
1097 case Builtin::BI__sync_and_and_fetch_8:
1098 case Builtin::BI__sync_and_and_fetch_16:
1099 case Builtin::BI__sync_or_and_fetch:
1100 case Builtin::BI__sync_or_and_fetch_1:
1101 case Builtin::BI__sync_or_and_fetch_2:
1102 case Builtin::BI__sync_or_and_fetch_4:
1103 case Builtin::BI__sync_or_and_fetch_8:
1104 case Builtin::BI__sync_or_and_fetch_16:
1105 case Builtin::BI__sync_xor_and_fetch:
1106 case Builtin::BI__sync_xor_and_fetch_1:
1107 case Builtin::BI__sync_xor_and_fetch_2:
1108 case Builtin::BI__sync_xor_and_fetch_4:
1109 case Builtin::BI__sync_xor_and_fetch_8:
1110 case Builtin::BI__sync_xor_and_fetch_16:
1111 case Builtin::BI__sync_nand_and_fetch:
1112 case Builtin::BI__sync_nand_and_fetch_1:
1113 case Builtin::BI__sync_nand_and_fetch_2:
1114 case Builtin::BI__sync_nand_and_fetch_4:
1115 case Builtin::BI__sync_nand_and_fetch_8:
1116 case Builtin::BI__sync_nand_and_fetch_16:
1117 case Builtin::BI__sync_val_compare_and_swap:
1118 case Builtin::BI__sync_val_compare_and_swap_1:
1119 case Builtin::BI__sync_val_compare_and_swap_2:
1120 case Builtin::BI__sync_val_compare_and_swap_4:
1121 case Builtin::BI__sync_val_compare_and_swap_8:
1122 case Builtin::BI__sync_val_compare_and_swap_16:
1123 case Builtin::BI__sync_bool_compare_and_swap:
1124 case Builtin::BI__sync_bool_compare_and_swap_1:
1125 case Builtin::BI__sync_bool_compare_and_swap_2:
1126 case Builtin::BI__sync_bool_compare_and_swap_4:
1127 case Builtin::BI__sync_bool_compare_and_swap_8:
1128 case Builtin::BI__sync_bool_compare_and_swap_16:
1129 case Builtin::BI__sync_lock_test_and_set:
1130 case Builtin::BI__sync_lock_test_and_set_1:
1131 case Builtin::BI__sync_lock_test_and_set_2:
1132 case Builtin::BI__sync_lock_test_and_set_4:
1133 case Builtin::BI__sync_lock_test_and_set_8:
1134 case Builtin::BI__sync_lock_test_and_set_16:
1135 case Builtin::BI__sync_lock_release:
1136 case Builtin::BI__sync_lock_release_1:
1137 case Builtin::BI__sync_lock_release_2:
1138 case Builtin::BI__sync_lock_release_4:
1139 case Builtin::BI__sync_lock_release_8:
1140 case Builtin::BI__sync_lock_release_16:
1141 case Builtin::BI__sync_swap:
1142 case Builtin::BI__sync_swap_1:
1143 case Builtin::BI__sync_swap_2:
1144 case Builtin::BI__sync_swap_4:
1145 case Builtin::BI__sync_swap_8:
1146 case Builtin::BI__sync_swap_16:
1147 return SemaBuiltinAtomicOverloaded(TheCallResult);
JF Bastiene77b48b2018-09-10 20:42:56 +00001148 case Builtin::BI__sync_synchronize:
1149 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1150 << TheCall->getCallee()->getSourceRange();
1151 break;
Aaron Ballman68d50642018-06-19 14:53:20 +00001152 case Builtin::BI__builtin_nontemporal_load:
1153 case Builtin::BI__builtin_nontemporal_store:
1154 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1155#define BUILTIN(ID, TYPE, ATTRS)
1156#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1157 case Builtin::BI##ID: \
1158 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1159#include "clang/Basic/Builtins.def"
1160 case Builtin::BI__annotation:
1161 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1162 return ExprError();
1163 break;
1164 case Builtin::BI__builtin_annotation:
1165 if (SemaBuiltinAnnotation(*this, TheCall))
1166 return ExprError();
1167 break;
1168 case Builtin::BI__builtin_addressof:
1169 if (SemaBuiltinAddressof(*this, TheCall))
1170 return ExprError();
1171 break;
1172 case Builtin::BI__builtin_add_overflow:
1173 case Builtin::BI__builtin_sub_overflow:
1174 case Builtin::BI__builtin_mul_overflow:
1175 if (SemaBuiltinOverflow(*this, TheCall))
1176 return ExprError();
1177 break;
1178 case Builtin::BI__builtin_operator_new:
1179 case Builtin::BI__builtin_operator_delete: {
1180 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1181 ExprResult Res =
1182 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1183 if (Res.isInvalid())
1184 CorrectDelayedTyposInExpr(TheCallResult.get());
1185 return Res;
1186 }
1187 case Builtin::BI__builtin_dump_struct: {
1188 // We first want to ensure we are called with 2 arguments
1189 if (checkArgCount(*this, TheCall, 2))
1190 return ExprError();
1191 // Ensure that the first argument is of type 'struct XX *'
1192 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1193 const QualType PtrArgType = PtrArg->getType();
1194 if (!PtrArgType->isPointerType() ||
1195 !PtrArgType->getPointeeType()->isRecordType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001196 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman68d50642018-06-19 14:53:20 +00001197 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1198 << "structure pointer";
1199 return ExprError();
Aaron Ballman06525342018-04-10 21:58:13 +00001200 }
1201
1202 // Ensure that the second argument is of type 'FunctionType'
1203 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1204 const QualType FnPtrArgType = FnPtrArg->getType();
1205 if (!FnPtrArgType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001206 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1207 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1208 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001209 return ExprError();
1210 }
1211
1212 const auto *FuncType =
1213 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1214
1215 if (!FuncType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001216 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1217 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1218 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001219 return ExprError();
1220 }
1221
1222 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1223 if (!FT->getNumParams()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001224 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001225 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1226 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1227 return ExprError();
1228 }
1229 QualType PT = FT->getParamType(0);
1230 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1231 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1232 !PT->getPointeeType().isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001233 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001234 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1235 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1236 return ExprError();
1237 }
1238 }
1239
1240 TheCall->setType(Context.IntTy);
1241 break;
1242 }
1243
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001244 // check secure string manipulation functions where overflows
1245 // are detectable at compile time
1246 case Builtin::BI__builtin___memcpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001247 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy");
1248 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001249 case Builtin::BI__builtin___memmove_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001250 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove");
1251 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001252 case Builtin::BI__builtin___memset_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001253 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset");
1254 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001255 case Builtin::BI__builtin___strlcat_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001256 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat");
1257 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001258 case Builtin::BI__builtin___strlcpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001259 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy");
1260 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001261 case Builtin::BI__builtin___strncat_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001262 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat");
1263 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001264 case Builtin::BI__builtin___strncpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001265 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy");
1266 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001267 case Builtin::BI__builtin___stpncpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001268 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy");
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001269 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001270 case Builtin::BI__builtin___memccpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001271 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy");
Steven Wu566c14e2014-09-24 04:37:33 +00001272 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001273 case Builtin::BI__builtin___snprintf_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001274 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf");
1275 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001276 case Builtin::BI__builtin___vsnprintf_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001277 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf");
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001278 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001279 case Builtin::BI__builtin_call_with_static_chain:
1280 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1281 return ExprError();
1282 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001283 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001284 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001285 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1286 diag::err_seh___except_block))
1287 return ExprError();
1288 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001289 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001290 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001291 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1292 diag::err_seh___except_filter))
1293 return ExprError();
1294 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001295 case Builtin::BI__GetExceptionInfo:
1296 if (checkArgCount(*this, TheCall, 1))
1297 return ExprError();
1298
1299 if (CheckCXXThrowOperand(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001300 TheCall->getBeginLoc(),
David Majnemerba3e5ec2015-03-13 18:26:17 +00001301 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1302 TheCall))
1303 return ExprError();
1304
1305 TheCall->setType(Context.VoidPtrTy);
1306 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001307 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001308 case Builtin::BIread_pipe:
1309 case Builtin::BIwrite_pipe:
1310 // Since those two functions are declared with var args, we need a semantic
1311 // check for the argument.
1312 if (SemaBuiltinRWPipe(*this, TheCall))
1313 return ExprError();
1314 break;
1315 case Builtin::BIreserve_read_pipe:
1316 case Builtin::BIreserve_write_pipe:
1317 case Builtin::BIwork_group_reserve_read_pipe:
1318 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001319 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1320 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001321 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001322 case Builtin::BIsub_group_reserve_read_pipe:
1323 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001324 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1325 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001326 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001327 break;
1328 case Builtin::BIcommit_read_pipe:
1329 case Builtin::BIcommit_write_pipe:
1330 case Builtin::BIwork_group_commit_read_pipe:
1331 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001332 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1333 return ExprError();
1334 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001335 case Builtin::BIsub_group_commit_read_pipe:
1336 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001337 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1338 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001339 return ExprError();
1340 break;
1341 case Builtin::BIget_pipe_num_packets:
1342 case Builtin::BIget_pipe_max_packets:
1343 if (SemaBuiltinPipePackets(*this, TheCall))
1344 return ExprError();
1345 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001346 case Builtin::BIto_global:
1347 case Builtin::BIto_local:
1348 case Builtin::BIto_private:
1349 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1350 return ExprError();
1351 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001352 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1353 case Builtin::BIenqueue_kernel:
1354 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1355 return ExprError();
1356 break;
1357 case Builtin::BIget_kernel_work_group_size:
1358 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1359 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1360 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001361 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001362 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1363 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1364 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1365 return ExprError();
1366 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001367 case Builtin::BI__builtin_os_log_format:
1368 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001369 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001370 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001371 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001372 }
Richard Smith760520b2014-06-03 23:27:44 +00001373
Nate Begeman4904e322010-06-08 02:47:44 +00001374 // Since the target specific builtins for each arch overlap, only check those
1375 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001376 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001377 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001378 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001379 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001380 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001381 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001382 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1383 return ExprError();
1384 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001385 case llvm::Triple::aarch64:
1386 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001387 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001388 return ExprError();
1389 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001390 case llvm::Triple::hexagon:
1391 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1392 return ExprError();
1393 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001394 case llvm::Triple::mips:
1395 case llvm::Triple::mipsel:
1396 case llvm::Triple::mips64:
1397 case llvm::Triple::mips64el:
1398 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1399 return ExprError();
1400 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001401 case llvm::Triple::systemz:
1402 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1403 return ExprError();
1404 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001405 case llvm::Triple::x86:
1406 case llvm::Triple::x86_64:
1407 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1408 return ExprError();
1409 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001410 case llvm::Triple::ppc:
1411 case llvm::Triple::ppc64:
1412 case llvm::Triple::ppc64le:
1413 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1414 return ExprError();
1415 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001416 default:
1417 break;
1418 }
1419 }
1420
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001421 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001422}
1423
Nate Begeman91e1fea2010-06-14 05:21:25 +00001424// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001425static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001426 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001427 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001428 switch (Type.getEltType()) {
1429 case NeonTypeFlags::Int8:
1430 case NeonTypeFlags::Poly8:
1431 return shift ? 7 : (8 << IsQuad) - 1;
1432 case NeonTypeFlags::Int16:
1433 case NeonTypeFlags::Poly16:
1434 return shift ? 15 : (4 << IsQuad) - 1;
1435 case NeonTypeFlags::Int32:
1436 return shift ? 31 : (2 << IsQuad) - 1;
1437 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001438 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001439 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001440 case NeonTypeFlags::Poly128:
1441 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001442 case NeonTypeFlags::Float16:
1443 assert(!shift && "cannot shift float types!");
1444 return (4 << IsQuad) - 1;
1445 case NeonTypeFlags::Float32:
1446 assert(!shift && "cannot shift float types!");
1447 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001448 case NeonTypeFlags::Float64:
1449 assert(!shift && "cannot shift float types!");
1450 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001451 }
David Blaikie8a40f702012-01-17 06:56:22 +00001452 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001453}
1454
Bob Wilsone4d77232011-11-08 05:04:11 +00001455/// getNeonEltType - Return the QualType corresponding to the elements of
1456/// the vector type specified by the NeonTypeFlags. This is used to check
1457/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001458static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001459 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001460 switch (Flags.getEltType()) {
1461 case NeonTypeFlags::Int8:
1462 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1463 case NeonTypeFlags::Int16:
1464 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1465 case NeonTypeFlags::Int32:
1466 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1467 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001468 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001469 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1470 else
1471 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1472 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001473 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001474 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001475 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001476 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001477 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001478 if (IsInt64Long)
1479 return Context.UnsignedLongTy;
1480 else
1481 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001482 case NeonTypeFlags::Poly128:
1483 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001484 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001485 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001486 case NeonTypeFlags::Float32:
1487 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001488 case NeonTypeFlags::Float64:
1489 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001490 }
David Blaikie8a40f702012-01-17 06:56:22 +00001491 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001492}
1493
Tim Northover12670412014-02-19 10:37:05 +00001494bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001495 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001496 uint64_t mask = 0;
1497 unsigned TV = 0;
1498 int PtrArgNum = -1;
1499 bool HasConstPtr = false;
1500 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001501#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001502#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001503#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001504#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001505 }
1506
1507 // For NEON intrinsics which are overloaded on vector element type, validate
1508 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001509 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001510 if (mask) {
1511 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1512 return true;
1513
1514 TV = Result.getLimitedValue(64);
1515 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001516 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1517 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001518 }
1519
1520 if (PtrArgNum >= 0) {
1521 // Check that pointer arguments have the specified type.
1522 Expr *Arg = TheCall->getArg(PtrArgNum);
1523 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1524 Arg = ICE->getSubExpr();
1525 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1526 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001527
Tim Northovera2ee4332014-03-29 15:09:45 +00001528 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001529 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1530 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001531 bool IsInt64Long =
1532 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1533 QualType EltTy =
1534 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001535 if (HasConstPtr)
1536 EltTy = EltTy.withConst();
1537 QualType LHSTy = Context.getPointerType(EltTy);
1538 AssignConvertType ConvTy;
1539 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1540 if (RHS.isInvalid())
1541 return true;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001542 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
Tim Northover2fe823a2013-08-01 09:23:19 +00001543 RHS.get(), AA_Assigning))
1544 return true;
1545 }
1546
1547 // For NEON intrinsics which take an immediate value as part of the
1548 // instruction, range check them here.
1549 unsigned i = 0, l = 0, u = 0;
1550 switch (BuiltinID) {
1551 default:
1552 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001553 #define GET_NEON_IMMEDIATE_CHECK
1554 #include "clang/Basic/arm_neon.inc"
1555 #include "clang/Basic/arm_fp16.inc"
1556 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001557 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001558
Richard Sandiford28940af2014-04-16 08:47:51 +00001559 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001560}
1561
Tim Northovera2ee4332014-03-29 15:09:45 +00001562bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1563 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001564 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001565 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001566 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001567 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001568 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001569 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1570 BuiltinID == AArch64::BI__builtin_arm_strex ||
1571 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001572 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001573 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001574 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1575 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1576 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001577
1578 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1579
1580 // Ensure that we have the proper number of arguments.
1581 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1582 return true;
1583
1584 // Inspect the pointer argument of the atomic builtin. This should always be
1585 // a pointer type, whose element is an integral scalar or pointer type.
1586 // Because it is a pointer type, we don't have to worry about any implicit
1587 // casts here.
1588 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1589 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1590 if (PointerArgRes.isInvalid())
1591 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001592 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001593
1594 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1595 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001596 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1597 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001598 return true;
1599 }
1600
1601 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1602 // task is to insert the appropriate casts into the AST. First work out just
1603 // what the appropriate type is.
1604 QualType ValType = pointerType->getPointeeType();
1605 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1606 if (IsLdrex)
1607 AddrType.addConst();
1608
1609 // Issue a warning if the cast is dodgy.
1610 CastKind CastNeeded = CK_NoOp;
1611 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1612 CastNeeded = CK_BitCast;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001613 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1614 << PointerArg->getType() << Context.getPointerType(AddrType)
1615 << AA_Passing << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001616 }
1617
1618 // Finally, do the cast and replace the argument with the corrected version.
1619 AddrType = Context.getPointerType(AddrType);
1620 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1621 if (PointerArgRes.isInvalid())
1622 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001623 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001624
1625 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1626
1627 // In general, we allow ints, floats and pointers to be loaded and stored.
1628 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1629 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001630 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1631 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001632 return true;
1633 }
1634
1635 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001636 if (Context.getTypeSize(ValType) > MaxWidth) {
1637 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001638 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1639 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001640 return true;
1641 }
1642
1643 switch (ValType.getObjCLifetime()) {
1644 case Qualifiers::OCL_None:
1645 case Qualifiers::OCL_ExplicitNone:
1646 // okay
1647 break;
1648
1649 case Qualifiers::OCL_Weak:
1650 case Qualifiers::OCL_Strong:
1651 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001652 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1653 << ValType << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001654 return true;
1655 }
1656
Tim Northover6aacd492013-07-16 09:47:53 +00001657 if (IsLdrex) {
1658 TheCall->setType(ValType);
1659 return false;
1660 }
1661
1662 // Initialize the argument to be stored.
1663 ExprResult ValArg = TheCall->getArg(0);
1664 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1665 Context, ValType, /*consume*/ false);
1666 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1667 if (ValArg.isInvalid())
1668 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001669 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001670
1671 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1672 // but the custom checker bypasses all default analysis.
1673 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001674 return false;
1675}
1676
Nate Begeman4904e322010-06-08 02:47:44 +00001677bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001678 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001679 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1680 BuiltinID == ARM::BI__builtin_arm_strex ||
1681 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001682 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001683 }
1684
Yi Kong26d104a2014-08-13 19:18:14 +00001685 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1686 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1687 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1688 }
1689
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001690 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1691 BuiltinID == ARM::BI__builtin_arm_wsr64)
1692 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1693
1694 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1695 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1696 BuiltinID == ARM::BI__builtin_arm_wsr ||
1697 BuiltinID == ARM::BI__builtin_arm_wsrp)
1698 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1699
Tim Northover12670412014-02-19 10:37:05 +00001700 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1701 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001702
Yi Kong4efadfb2014-07-03 16:01:25 +00001703 // For intrinsics which take an immediate value as part of the instruction,
1704 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001705 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001706 switch (BuiltinID) {
1707 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001708 case ARM::BI__builtin_arm_ssat:
1709 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1710 case ARM::BI__builtin_arm_usat:
1711 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1712 case ARM::BI__builtin_arm_ssat16:
1713 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1714 case ARM::BI__builtin_arm_usat16:
1715 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001716 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001717 case ARM::BI__builtin_arm_vcvtr_d:
1718 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001719 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001720 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001721 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001722 case ARM::BI__builtin_arm_dbg:
1723 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001724 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001725}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001726
Tim Northover573cbee2014-05-24 12:52:07 +00001727bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001728 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001729 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001730 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1731 BuiltinID == AArch64::BI__builtin_arm_strex ||
1732 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001733 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1734 }
1735
Yi Konga5548432014-08-13 19:18:20 +00001736 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1737 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1738 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1739 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1740 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1741 }
1742
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001743 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1744 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001745 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001746
1747 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1748 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1749 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1750 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1751 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1752
Mandeep Singh Grang2147b1a2018-10-18 23:35:35 +00001753 // Only check the valid encoding range. Any constant in this range would be
1754 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1755 // an exception for incorrect registers. This matches MSVC behavior.
1756 if (BuiltinID == AArch64::BI_ReadStatusReg ||
1757 BuiltinID == AArch64::BI_WriteStatusReg)
1758 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1759
Mandeep Singh Grangecc82ef2018-10-04 22:32:42 +00001760 if (BuiltinID == AArch64::BI__getReg)
1761 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1762
Tim Northovera2ee4332014-03-29 15:09:45 +00001763 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1764 return true;
1765
Yi Kong19a29ac2014-07-17 10:52:06 +00001766 // For intrinsics which take an immediate value as part of the instruction,
1767 // range check them here.
1768 unsigned i = 0, l = 0, u = 0;
1769 switch (BuiltinID) {
1770 default: return false;
1771 case AArch64::BI__builtin_arm_dmb:
1772 case AArch64::BI__builtin_arm_dsb:
1773 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1774 }
1775
Yi Kong19a29ac2014-07-17 10:52:06 +00001776 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001777}
1778
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001779bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001780 struct BuiltinAndString {
1781 unsigned BuiltinID;
1782 const char *Str;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001783 };
1784
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001785 static BuiltinAndString ValidCPU[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00001786 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1787 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1788 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1789 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1790 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1791 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1792 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1793 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1794 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1795 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1796 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1797 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1798 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1799 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1800 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1801 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1802 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1803 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1804 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1805 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1806 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1807 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1808 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001809 };
1810
1811 static BuiltinAndString ValidHVX[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00001812 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1813 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1814 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1815 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1816 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1817 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1818 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1819 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1820 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1821 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1822 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1823 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1824 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1825 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1826 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1827 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1828 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1829 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1830 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1831 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1832 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1833 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1834 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1835 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1836 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1837 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1838 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
1839 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
1840 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
1841 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
1842 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
1843 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
1844 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
1845 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
1846 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
1847 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
1848 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
1849 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
1850 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
1851 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
1852 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
1853 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
1854 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
1855 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
1856 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
1857 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
1858 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
1859 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
1860 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
1861 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
1862 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
1863 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
1864 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
1865 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
1866 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
1867 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
1868 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
1869 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
1870 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
1871 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
1872 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
1873 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
1874 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
1875 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
1876 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
1877 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
1878 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
1879 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
1880 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
1881 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
1882 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
1883 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
1884 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
1885 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
1886 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
1887 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
1888 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
1889 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
1890 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
1891 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
1892 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
1893 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
1894 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
1895 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
1896 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
1897 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
1898 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
1899 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
1900 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
1901 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
1902 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
1903 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
1904 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
1905 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
1906 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
1907 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
1908 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
1909 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
1910 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
1911 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
1912 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
1913 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
1914 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
1915 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
1916 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
1917 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
1918 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
1919 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
1920 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
1921 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
1922 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
1923 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
1924 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
1925 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
1926 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
1927 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
1928 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
1929 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
1930 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
1931 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
1932 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
1933 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
1934 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
1935 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
1936 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
1937 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
1938 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
1939 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
1940 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
1941 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
1942 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
1943 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
1944 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
1945 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
1946 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
1947 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
1948 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
1949 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
1950 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
1951 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
1952 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
1953 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
1954 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
1955 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
1956 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
1957 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
1958 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
1959 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
1960 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
1961 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
1962 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
1963 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
1964 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
1965 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
1966 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
1967 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
1968 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
1969 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
1970 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
1971 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
1972 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
1973 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
1974 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
1975 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
1976 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
1977 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
1978 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
1979 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
1980 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
1981 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
1982 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
1983 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
1984 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
1985 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
1986 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
1987 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
1988 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
1989 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
1990 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
1991 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
1992 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
1993 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
1994 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
1995 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
1996 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
1997 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
1998 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
1999 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2000 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2001 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2002 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2003 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2004 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2005 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2006 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2007 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2008 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2009 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2010 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2011 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2012 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2013 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2014 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2015 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2016 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2017 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2018 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2019 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2020 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2021 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2022 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2023 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2024 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2025 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2026 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2027 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2028 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2029 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2030 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2031 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2032 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2033 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2034 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2035 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2036 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2037 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2038 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2039 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2040 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2041 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2042 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2043 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2044 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2045 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2046 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2047 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2048 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2049 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2050 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2051 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2052 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2053 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2054 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2055 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2056 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2057 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2058 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2059 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2060 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2061 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2062 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2063 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2064 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2065 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2066 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2067 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2068 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2069 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2070 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2071 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2072 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2073 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2074 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2075 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2076 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2077 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2078 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2079 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2080 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2081 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2082 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2083 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2084 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2085 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2086 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2087 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2088 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2089 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2090 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2091 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2092 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2093 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2094 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2095 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2096 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2097 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2098 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2099 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2100 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2101 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2102 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2103 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2104 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2105 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2106 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2107 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2108 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2109 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2110 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2111 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2112 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2113 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2114 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2115 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2116 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2117 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2118 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2119 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2120 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2121 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2122 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2123 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2124 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2125 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2126 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2127 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2128 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2129 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2130 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2131 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2132 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2133 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2134 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2135 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2136 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2137 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2138 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2139 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2140 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2141 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2142 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2143 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2144 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2145 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2146 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2147 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2148 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2149 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2150 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2151 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2152 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2153 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2154 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2155 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2156 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2157 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2158 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2159 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2160 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2161 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2162 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2163 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2164 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2165 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2166 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2167 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2168 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2169 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2170 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2171 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2172 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2173 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2174 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2175 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2176 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2177 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2178 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2179 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2180 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2181 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2182 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2183 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2184 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2185 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2186 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2187 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2188 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2189 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2190 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2191 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2192 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2193 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2194 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2195 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2196 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2197 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2198 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2199 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2200 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2201 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2202 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2203 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2204 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2205 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2206 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2207 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2208 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2209 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2210 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2211 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2212 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2213 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2214 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2215 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2216 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2217 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2218 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2219 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2220 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2221 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2222 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2223 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2224 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2225 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2226 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2227 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2228 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2229 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2230 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2231 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2232 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2233 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2234 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2235 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2236 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2237 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2238 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2239 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2240 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2241 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2242 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2243 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2244 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2245 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2246 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2247 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2248 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2249 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2250 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2251 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2252 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2253 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2254 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2255 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2256 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2257 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2258 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2259 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2260 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2261 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2262 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2263 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2264 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2265 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2266 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2267 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2268 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2269 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2270 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2271 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2272 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2273 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2274 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2275 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2304 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2305 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2306 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2307 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2308 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2309 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2310 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2311 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2312 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2313 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2314 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2315 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2316 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2317 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2318 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2319 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2320 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2321 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2322 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2323 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2324 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2325 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2326 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2327 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2328 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2329 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2330 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2331 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2332 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2333 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2334 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2335 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2336 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2337 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2338 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2339 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2340 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2341 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2342 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2343 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2344 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2345 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2346 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2347 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2348 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2349 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2350 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2351 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2352 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2353 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2354 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2355 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2356 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2357 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2358 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2359 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2360 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2361 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2362 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2363 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2364 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2365 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2366 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2367 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2368 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2369 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2370 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2371 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2372 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2373 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2374 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2375 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2376 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2377 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2378 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2379 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002380 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2381 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2382 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2383 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002384 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2385 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2386 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2387 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2388 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2389 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2390 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2391 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2392 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2393 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2394 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2395 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2396 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2397 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2398 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2399 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2400 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2401 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2402 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2403 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2404 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2405 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2406 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2407 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002408 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2409 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2410 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2411 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002412 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2413 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2414 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2415 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2416 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2417 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2418 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2419 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2420 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2421 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2422 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2423 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2424 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2425 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2426 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2427 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2428 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2429 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2430 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2431 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2432 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2433 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2434 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2435 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2436 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2437 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2438 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2439 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2440 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2441 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2442 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2443 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2444 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2445 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2446 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2447 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2448 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2449 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2450 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2451 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2452 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2453 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2454 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2455 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2456 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2457 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2458 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2459 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2460 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2461 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2462 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2463 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2464 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2465 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2466 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2467 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2468 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2469 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2470 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2471 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2472 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2473 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2474 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2475 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2476 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2477 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2478 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2479 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2480 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2481 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2482 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2483 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2484 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2485 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2486 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2487 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2488 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2489 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2490 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2491 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2492 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2493 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2494 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2495 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2496 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2497 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2498 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2499 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2500 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2501 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2502 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2503 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2504 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2505 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2506 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2507 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2508 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2509 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2510 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2511 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2512 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2513 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2514 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2515 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2516 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2517 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2518 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2519 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2520 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2521 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2522 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2523 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2524 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2525 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2526 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2527 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2528 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2529 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2530 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2531 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2532 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2533 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2534 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2535 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2536 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2537 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2538 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2539 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2540 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2541 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2542 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2543 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002544 };
2545
2546 // Sort the tables on first execution so we can binary search them.
2547 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2548 return LHS.BuiltinID < RHS.BuiltinID;
2549 };
2550 static const bool SortOnce =
2551 (std::sort(std::begin(ValidCPU), std::end(ValidCPU), SortCmp),
2552 std::sort(std::begin(ValidHVX), std::end(ValidHVX), SortCmp), true);
2553 (void)SortOnce;
2554 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2555 return BI.BuiltinID < BuiltinID;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002556 };
2557
2558 const TargetInfo &TI = Context.getTargetInfo();
2559
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002560 const BuiltinAndString *FC =
2561 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2562 LowerBoundCmp);
2563 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002564 const TargetOptions &Opts = TI.getTargetOpts();
2565 StringRef CPU = Opts.CPU;
2566 if (!CPU.empty()) {
2567 assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2568 CPU.consume_front("hexagon");
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002569 SmallVector<StringRef, 3> CPUs;
2570 StringRef(FC->Str).split(CPUs, ',');
2571 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002572 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002573 diag::err_hexagon_builtin_unsupported_cpu);
2574 }
2575 }
2576
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002577 const BuiltinAndString *FH =
2578 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2579 LowerBoundCmp);
2580 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002581 if (!TI.hasFeature("hvx"))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002582 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002583 diag::err_hexagon_builtin_requires_hvx);
2584
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002585 SmallVector<StringRef, 3> HVXs;
2586 StringRef(FH->Str).split(HVXs, ',');
2587 bool IsValid = llvm::any_of(HVXs,
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002588 [&TI] (StringRef V) {
2589 std::string F = "hvx" + V.str();
2590 return TI.hasFeature(F);
2591 });
2592 if (!IsValid)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002593 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002594 diag::err_hexagon_builtin_unsupported_hvx);
2595 }
2596
2597 return false;
2598}
2599
2600bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002601 struct ArgInfo {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002602 uint8_t OpNum;
2603 bool IsSigned;
2604 uint8_t BitWidth;
2605 uint8_t Align;
2606 };
2607 struct BuiltinInfo {
2608 unsigned BuiltinID;
2609 ArgInfo Infos[2];
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002610 };
2611
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002612 static BuiltinInfo Infos[] = {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002613 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2614 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2615 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2616 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
2617 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2618 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2619 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2620 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2621 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2622 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2623 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2624
2625 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2626 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2627 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2628 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2629 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2630 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2631 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2632 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2633 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2634 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2635 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2636
2637 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2638 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2639 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2640 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2641 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2642 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2643 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2644 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2645 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2646 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2647 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2648 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2649 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2650 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2651 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2652 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2653 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2654 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2655 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2656 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2657 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2658 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2659 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2660 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2661 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2662 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2663 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2664 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2665 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2666 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2667 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2668 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2669 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2670 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2671 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2672 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2673 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2674 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2675 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2676 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2677 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2678 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2679 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2680 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2681 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2682 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2683 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2684 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2685 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2686 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2687 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2688 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2689 {{ 1, false, 6, 0 }} },
2690 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2691 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2692 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2693 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2694 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2695 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2696 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2697 {{ 1, false, 5, 0 }} },
2698 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
2699 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
2700 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
2701 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
2702 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
2703 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
2704 { 2, false, 5, 0 }} },
2705 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
2706 { 2, false, 6, 0 }} },
2707 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
2708 { 3, false, 5, 0 }} },
2709 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
2710 { 3, false, 6, 0 }} },
2711 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
2712 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
2713 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
2714 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
2715 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
2716 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
2717 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
2718 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
2719 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
2720 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
2721 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
2722 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
2723 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
2724 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
2725 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
2726 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2727 {{ 2, false, 4, 0 },
2728 { 3, false, 5, 0 }} },
2729 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2730 {{ 2, false, 4, 0 },
2731 { 3, false, 5, 0 }} },
2732 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2733 {{ 2, false, 4, 0 },
2734 { 3, false, 5, 0 }} },
2735 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2736 {{ 2, false, 4, 0 },
2737 { 3, false, 5, 0 }} },
2738 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
2739 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
2740 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
2741 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
2742 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
2743 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
2744 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
2745 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
2746 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
2747 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
2748 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
2749 { 2, false, 5, 0 }} },
2750 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
2751 { 2, false, 6, 0 }} },
2752 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
2753 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
2754 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
2755 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
2756 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
2757 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
2758 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
2759 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
2760 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2761 {{ 1, false, 4, 0 }} },
2762 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
2763 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2764 {{ 1, false, 4, 0 }} },
2765 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
2766 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
2767 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
2768 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
2769 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
2770 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
2771 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
2772 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
2773 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
2774 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
2775 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
2776 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
2777 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
2778 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
2779 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
2780 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
2781 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
2782 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
2783 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
2784 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2785 {{ 3, false, 1, 0 }} },
2786 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
2787 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
2788 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
2789 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2790 {{ 3, false, 1, 0 }} },
2791 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
2792 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
2793 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
2794 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2795 {{ 3, false, 1, 0 }} },
2796 };
2797
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002798 // Use a dynamically initialized static to sort the table exactly once on
2799 // first run.
2800 static const bool SortOnce =
2801 (std::sort(std::begin(Infos), std::end(Infos),
2802 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2803 return LHS.BuiltinID < RHS.BuiltinID;
2804 }),
2805 true);
2806 (void)SortOnce;
2807
2808 const BuiltinInfo *F =
2809 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2810 [](const BuiltinInfo &BI, unsigned BuiltinID) {
2811 return BI.BuiltinID < BuiltinID;
2812 });
2813 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002814 return false;
2815
2816 bool Error = false;
2817
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002818 for (const ArgInfo &A : F->Infos) {
2819 // Ignore empty ArgInfo elements.
2820 if (A.BitWidth == 0)
2821 continue;
2822
2823 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2824 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002825 if (!A.Align) {
2826 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2827 } else {
2828 unsigned M = 1 << A.Align;
2829 Min *= M;
2830 Max *= M;
2831 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2832 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2833 }
2834 }
2835 return Error;
2836}
2837
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002838bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2839 CallExpr *TheCall) {
2840 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2841 CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2842}
2843
2844
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002845// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2846// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2847// ordering for DSP is unspecified. MSA is ordered by the data format used
2848// by the underlying instruction i.e., df/m, df/n and then by size.
2849//
2850// FIXME: The size tests here should instead be tablegen'd along with the
2851// definitions from include/clang/Basic/BuiltinsMips.def.
2852// FIXME: GCC is strict on signedness for some of these intrinsics, we should
2853// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002854bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002855 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002856 switch (BuiltinID) {
2857 default: return false;
2858 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2859 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00002860 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2861 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2862 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2863 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2864 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002865 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002866 // df/m field.
2867 // These intrinsics take an unsigned 3 bit immediate.
2868 case Mips::BI__builtin_msa_bclri_b:
2869 case Mips::BI__builtin_msa_bnegi_b:
2870 case Mips::BI__builtin_msa_bseti_b:
2871 case Mips::BI__builtin_msa_sat_s_b:
2872 case Mips::BI__builtin_msa_sat_u_b:
2873 case Mips::BI__builtin_msa_slli_b:
2874 case Mips::BI__builtin_msa_srai_b:
2875 case Mips::BI__builtin_msa_srari_b:
2876 case Mips::BI__builtin_msa_srli_b:
2877 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2878 case Mips::BI__builtin_msa_binsli_b:
2879 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2880 // These intrinsics take an unsigned 4 bit immediate.
2881 case Mips::BI__builtin_msa_bclri_h:
2882 case Mips::BI__builtin_msa_bnegi_h:
2883 case Mips::BI__builtin_msa_bseti_h:
2884 case Mips::BI__builtin_msa_sat_s_h:
2885 case Mips::BI__builtin_msa_sat_u_h:
2886 case Mips::BI__builtin_msa_slli_h:
2887 case Mips::BI__builtin_msa_srai_h:
2888 case Mips::BI__builtin_msa_srari_h:
2889 case Mips::BI__builtin_msa_srli_h:
2890 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2891 case Mips::BI__builtin_msa_binsli_h:
2892 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002893 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002894 // The first block of intrinsics actually have an unsigned 5 bit field,
2895 // not a df/n field.
2896 case Mips::BI__builtin_msa_clei_u_b:
2897 case Mips::BI__builtin_msa_clei_u_h:
2898 case Mips::BI__builtin_msa_clei_u_w:
2899 case Mips::BI__builtin_msa_clei_u_d:
2900 case Mips::BI__builtin_msa_clti_u_b:
2901 case Mips::BI__builtin_msa_clti_u_h:
2902 case Mips::BI__builtin_msa_clti_u_w:
2903 case Mips::BI__builtin_msa_clti_u_d:
2904 case Mips::BI__builtin_msa_maxi_u_b:
2905 case Mips::BI__builtin_msa_maxi_u_h:
2906 case Mips::BI__builtin_msa_maxi_u_w:
2907 case Mips::BI__builtin_msa_maxi_u_d:
2908 case Mips::BI__builtin_msa_mini_u_b:
2909 case Mips::BI__builtin_msa_mini_u_h:
2910 case Mips::BI__builtin_msa_mini_u_w:
2911 case Mips::BI__builtin_msa_mini_u_d:
2912 case Mips::BI__builtin_msa_addvi_b:
2913 case Mips::BI__builtin_msa_addvi_h:
2914 case Mips::BI__builtin_msa_addvi_w:
2915 case Mips::BI__builtin_msa_addvi_d:
2916 case Mips::BI__builtin_msa_bclri_w:
2917 case Mips::BI__builtin_msa_bnegi_w:
2918 case Mips::BI__builtin_msa_bseti_w:
2919 case Mips::BI__builtin_msa_sat_s_w:
2920 case Mips::BI__builtin_msa_sat_u_w:
2921 case Mips::BI__builtin_msa_slli_w:
2922 case Mips::BI__builtin_msa_srai_w:
2923 case Mips::BI__builtin_msa_srari_w:
2924 case Mips::BI__builtin_msa_srli_w:
2925 case Mips::BI__builtin_msa_srlri_w:
2926 case Mips::BI__builtin_msa_subvi_b:
2927 case Mips::BI__builtin_msa_subvi_h:
2928 case Mips::BI__builtin_msa_subvi_w:
2929 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2930 case Mips::BI__builtin_msa_binsli_w:
2931 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2932 // These intrinsics take an unsigned 6 bit immediate.
2933 case Mips::BI__builtin_msa_bclri_d:
2934 case Mips::BI__builtin_msa_bnegi_d:
2935 case Mips::BI__builtin_msa_bseti_d:
2936 case Mips::BI__builtin_msa_sat_s_d:
2937 case Mips::BI__builtin_msa_sat_u_d:
2938 case Mips::BI__builtin_msa_slli_d:
2939 case Mips::BI__builtin_msa_srai_d:
2940 case Mips::BI__builtin_msa_srari_d:
2941 case Mips::BI__builtin_msa_srli_d:
2942 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2943 case Mips::BI__builtin_msa_binsli_d:
2944 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2945 // These intrinsics take a signed 5 bit immediate.
2946 case Mips::BI__builtin_msa_ceqi_b:
2947 case Mips::BI__builtin_msa_ceqi_h:
2948 case Mips::BI__builtin_msa_ceqi_w:
2949 case Mips::BI__builtin_msa_ceqi_d:
2950 case Mips::BI__builtin_msa_clti_s_b:
2951 case Mips::BI__builtin_msa_clti_s_h:
2952 case Mips::BI__builtin_msa_clti_s_w:
2953 case Mips::BI__builtin_msa_clti_s_d:
2954 case Mips::BI__builtin_msa_clei_s_b:
2955 case Mips::BI__builtin_msa_clei_s_h:
2956 case Mips::BI__builtin_msa_clei_s_w:
2957 case Mips::BI__builtin_msa_clei_s_d:
2958 case Mips::BI__builtin_msa_maxi_s_b:
2959 case Mips::BI__builtin_msa_maxi_s_h:
2960 case Mips::BI__builtin_msa_maxi_s_w:
2961 case Mips::BI__builtin_msa_maxi_s_d:
2962 case Mips::BI__builtin_msa_mini_s_b:
2963 case Mips::BI__builtin_msa_mini_s_h:
2964 case Mips::BI__builtin_msa_mini_s_w:
2965 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2966 // These intrinsics take an unsigned 8 bit immediate.
2967 case Mips::BI__builtin_msa_andi_b:
2968 case Mips::BI__builtin_msa_nori_b:
2969 case Mips::BI__builtin_msa_ori_b:
2970 case Mips::BI__builtin_msa_shf_b:
2971 case Mips::BI__builtin_msa_shf_h:
2972 case Mips::BI__builtin_msa_shf_w:
2973 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2974 case Mips::BI__builtin_msa_bseli_b:
2975 case Mips::BI__builtin_msa_bmnzi_b:
2976 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2977 // df/n format
2978 // These intrinsics take an unsigned 4 bit immediate.
2979 case Mips::BI__builtin_msa_copy_s_b:
2980 case Mips::BI__builtin_msa_copy_u_b:
2981 case Mips::BI__builtin_msa_insve_b:
2982 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002983 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2984 // These intrinsics take an unsigned 3 bit immediate.
2985 case Mips::BI__builtin_msa_copy_s_h:
2986 case Mips::BI__builtin_msa_copy_u_h:
2987 case Mips::BI__builtin_msa_insve_h:
2988 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002989 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2990 // These intrinsics take an unsigned 2 bit immediate.
2991 case Mips::BI__builtin_msa_copy_s_w:
2992 case Mips::BI__builtin_msa_copy_u_w:
2993 case Mips::BI__builtin_msa_insve_w:
2994 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002995 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2996 // These intrinsics take an unsigned 1 bit immediate.
2997 case Mips::BI__builtin_msa_copy_s_d:
2998 case Mips::BI__builtin_msa_copy_u_d:
2999 case Mips::BI__builtin_msa_insve_d:
3000 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003001 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3002 // Memory offsets and immediate loads.
3003 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00003004 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003005 case Mips::BI__builtin_msa_ldi_h:
3006 case Mips::BI__builtin_msa_ldi_w:
3007 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
Aleksandar Beserminjie5921162018-11-07 11:37:05 +00003008 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3009 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3010 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3011 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3012 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3013 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3014 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3015 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00003016 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003017
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003018 if (!m)
3019 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3020
3021 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3022 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003023}
3024
Kit Bartone50adcb2015-03-30 19:40:59 +00003025bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3026 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003027 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3028 BuiltinID == PPC::BI__builtin_divdeu ||
3029 BuiltinID == PPC::BI__builtin_bpermd;
3030 bool IsTarget64Bit = Context.getTargetInfo()
3031 .getTypeWidth(Context
3032 .getTargetInfo()
3033 .getIntPtrType()) == 64;
3034 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3035 BuiltinID == PPC::BI__builtin_divweu ||
3036 BuiltinID == PPC::BI__builtin_divde ||
3037 BuiltinID == PPC::BI__builtin_divdeu;
3038
3039 if (Is64BitBltin && !IsTarget64Bit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003040 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3041 << TheCall->getSourceRange();
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003042
3043 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3044 (BuiltinID == PPC::BI__builtin_bpermd &&
3045 !Context.getTargetInfo().hasFeature("bpermd")))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003046 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003047 << TheCall->getSourceRange();
3048
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003049 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3050 if (!Context.getTargetInfo().hasFeature("vsx"))
3051 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3052 << TheCall->getSourceRange();
3053 return false;
3054 };
3055
Kit Bartone50adcb2015-03-30 19:40:59 +00003056 switch (BuiltinID) {
3057 default: return false;
3058 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3059 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3060 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3061 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3062 case PPC::BI__builtin_tbegin:
3063 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3064 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3065 case PPC::BI__builtin_tabortwc:
3066 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3067 case PPC::BI__builtin_tabortwci:
3068 case PPC::BI__builtin_tabortdci:
3069 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3070 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00003071 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00003072 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00003073 return SemaBuiltinVSX(TheCall);
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003074 case PPC::BI__builtin_unpack_vector_int128:
3075 return SemaVSXCheck(TheCall) ||
3076 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3077 case PPC::BI__builtin_pack_vector_int128:
3078 return SemaVSXCheck(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00003079 }
3080 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3081}
3082
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003083bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3084 CallExpr *TheCall) {
3085 if (BuiltinID == SystemZ::BI__builtin_tabort) {
3086 Expr *Arg = TheCall->getArg(0);
3087 llvm::APSInt AbortCode(32);
3088 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3089 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003090 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003091 << Arg->getSourceRange();
3092 }
3093
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003094 // For intrinsics which take an immediate value as part of the instruction,
3095 // range check them here.
3096 unsigned i = 0, l = 0, u = 0;
3097 switch (BuiltinID) {
3098 default: return false;
3099 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3100 case SystemZ::BI__builtin_s390_verimb:
3101 case SystemZ::BI__builtin_s390_verimh:
3102 case SystemZ::BI__builtin_s390_verimf:
3103 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3104 case SystemZ::BI__builtin_s390_vfaeb:
3105 case SystemZ::BI__builtin_s390_vfaeh:
3106 case SystemZ::BI__builtin_s390_vfaef:
3107 case SystemZ::BI__builtin_s390_vfaebs:
3108 case SystemZ::BI__builtin_s390_vfaehs:
3109 case SystemZ::BI__builtin_s390_vfaefs:
3110 case SystemZ::BI__builtin_s390_vfaezb:
3111 case SystemZ::BI__builtin_s390_vfaezh:
3112 case SystemZ::BI__builtin_s390_vfaezf:
3113 case SystemZ::BI__builtin_s390_vfaezbs:
3114 case SystemZ::BI__builtin_s390_vfaezhs:
3115 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003116 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003117 case SystemZ::BI__builtin_s390_vfidb:
3118 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3119 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003120 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003121 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3122 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3123 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3124 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3125 case SystemZ::BI__builtin_s390_vstrcb:
3126 case SystemZ::BI__builtin_s390_vstrch:
3127 case SystemZ::BI__builtin_s390_vstrcf:
3128 case SystemZ::BI__builtin_s390_vstrczb:
3129 case SystemZ::BI__builtin_s390_vstrczh:
3130 case SystemZ::BI__builtin_s390_vstrczf:
3131 case SystemZ::BI__builtin_s390_vstrcbs:
3132 case SystemZ::BI__builtin_s390_vstrchs:
3133 case SystemZ::BI__builtin_s390_vstrcfs:
3134 case SystemZ::BI__builtin_s390_vstrczbs:
3135 case SystemZ::BI__builtin_s390_vstrczhs:
3136 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003137 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3138 case SystemZ::BI__builtin_s390_vfminsb:
3139 case SystemZ::BI__builtin_s390_vfmaxsb:
3140 case SystemZ::BI__builtin_s390_vfmindb:
3141 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003142 }
3143 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003144}
3145
Craig Topper5ba2c502015-11-07 08:08:31 +00003146/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3147/// This checks that the target supports __builtin_cpu_supports and
3148/// that the string argument is constant and valid.
3149static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3150 Expr *Arg = TheCall->getArg(0);
3151
3152 // Check if the argument is a string literal.
3153 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003154 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper5ba2c502015-11-07 08:08:31 +00003155 << Arg->getSourceRange();
3156
3157 // Check the contents of the string.
3158 StringRef Feature =
3159 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3160 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003161 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
Craig Topper5ba2c502015-11-07 08:08:31 +00003162 << Arg->getSourceRange();
3163 return false;
3164}
3165
Craig Topper699ae0c2017-08-10 20:28:30 +00003166/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3167/// This checks that the target supports __builtin_cpu_is and
3168/// that the string argument is constant and valid.
3169static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3170 Expr *Arg = TheCall->getArg(0);
3171
3172 // Check if the argument is a string literal.
3173 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003174 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper699ae0c2017-08-10 20:28:30 +00003175 << Arg->getSourceRange();
3176
3177 // Check the contents of the string.
3178 StringRef Feature =
3179 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3180 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003181 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
Craig Topper699ae0c2017-08-10 20:28:30 +00003182 << Arg->getSourceRange();
3183 return false;
3184}
3185
Craig Toppera7e253e2016-09-23 04:48:31 +00003186// Check if the rounding mode is legal.
3187bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3188 // Indicates if this instruction has rounding control or just SAE.
3189 bool HasRC = false;
3190
3191 unsigned ArgNum = 0;
3192 switch (BuiltinID) {
3193 default:
3194 return false;
3195 case X86::BI__builtin_ia32_vcvttsd2si32:
3196 case X86::BI__builtin_ia32_vcvttsd2si64:
3197 case X86::BI__builtin_ia32_vcvttsd2usi32:
3198 case X86::BI__builtin_ia32_vcvttsd2usi64:
3199 case X86::BI__builtin_ia32_vcvttss2si32:
3200 case X86::BI__builtin_ia32_vcvttss2si64:
3201 case X86::BI__builtin_ia32_vcvttss2usi32:
3202 case X86::BI__builtin_ia32_vcvttss2usi64:
3203 ArgNum = 1;
3204 break;
Craig Topper2da60bc2018-06-21 05:01:01 +00003205 case X86::BI__builtin_ia32_maxpd512:
3206 case X86::BI__builtin_ia32_maxps512:
3207 case X86::BI__builtin_ia32_minpd512:
3208 case X86::BI__builtin_ia32_minps512:
3209 ArgNum = 2;
3210 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003211 case X86::BI__builtin_ia32_cvtps2pd512_mask:
3212 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3213 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3214 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3215 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3216 case X86::BI__builtin_ia32_cvttps2dq512_mask:
3217 case X86::BI__builtin_ia32_cvttps2qq512_mask:
3218 case X86::BI__builtin_ia32_cvttps2udq512_mask:
3219 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3220 case X86::BI__builtin_ia32_exp2pd_mask:
3221 case X86::BI__builtin_ia32_exp2ps_mask:
3222 case X86::BI__builtin_ia32_getexppd512_mask:
3223 case X86::BI__builtin_ia32_getexpps512_mask:
3224 case X86::BI__builtin_ia32_rcp28pd_mask:
3225 case X86::BI__builtin_ia32_rcp28ps_mask:
3226 case X86::BI__builtin_ia32_rsqrt28pd_mask:
3227 case X86::BI__builtin_ia32_rsqrt28ps_mask:
3228 case X86::BI__builtin_ia32_vcomisd:
3229 case X86::BI__builtin_ia32_vcomiss:
3230 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3231 ArgNum = 3;
3232 break;
3233 case X86::BI__builtin_ia32_cmppd512_mask:
3234 case X86::BI__builtin_ia32_cmpps512_mask:
3235 case X86::BI__builtin_ia32_cmpsd_mask:
3236 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003237 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003238 case X86::BI__builtin_ia32_getexpsd128_round_mask:
3239 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003240 case X86::BI__builtin_ia32_maxsd_round_mask:
3241 case X86::BI__builtin_ia32_maxss_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003242 case X86::BI__builtin_ia32_minsd_round_mask:
3243 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003244 case X86::BI__builtin_ia32_rcp28sd_round_mask:
3245 case X86::BI__builtin_ia32_rcp28ss_round_mask:
3246 case X86::BI__builtin_ia32_reducepd512_mask:
3247 case X86::BI__builtin_ia32_reduceps512_mask:
3248 case X86::BI__builtin_ia32_rndscalepd_mask:
3249 case X86::BI__builtin_ia32_rndscaleps_mask:
3250 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3251 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3252 ArgNum = 4;
3253 break;
3254 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003255 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003256 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003257 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003258 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003259 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003260 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003261 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003262 case X86::BI__builtin_ia32_rangepd512_mask:
3263 case X86::BI__builtin_ia32_rangeps512_mask:
3264 case X86::BI__builtin_ia32_rangesd128_round_mask:
3265 case X86::BI__builtin_ia32_rangess128_round_mask:
3266 case X86::BI__builtin_ia32_reducesd_mask:
3267 case X86::BI__builtin_ia32_reducess_mask:
3268 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3269 case X86::BI__builtin_ia32_rndscaless_round_mask:
3270 ArgNum = 5;
3271 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003272 case X86::BI__builtin_ia32_vcvtsd2si64:
3273 case X86::BI__builtin_ia32_vcvtsd2si32:
3274 case X86::BI__builtin_ia32_vcvtsd2usi32:
3275 case X86::BI__builtin_ia32_vcvtsd2usi64:
3276 case X86::BI__builtin_ia32_vcvtss2si32:
3277 case X86::BI__builtin_ia32_vcvtss2si64:
3278 case X86::BI__builtin_ia32_vcvtss2usi32:
3279 case X86::BI__builtin_ia32_vcvtss2usi64:
Craig Topper8bf793f2018-06-29 05:43:33 +00003280 case X86::BI__builtin_ia32_sqrtpd512:
3281 case X86::BI__builtin_ia32_sqrtps512:
Craig Topper7609f1c2016-10-01 21:03:50 +00003282 ArgNum = 1;
3283 HasRC = true;
3284 break;
Craig Topper3614b412018-06-10 06:01:42 +00003285 case X86::BI__builtin_ia32_addpd512:
3286 case X86::BI__builtin_ia32_addps512:
3287 case X86::BI__builtin_ia32_divpd512:
3288 case X86::BI__builtin_ia32_divps512:
3289 case X86::BI__builtin_ia32_mulpd512:
3290 case X86::BI__builtin_ia32_mulps512:
3291 case X86::BI__builtin_ia32_subpd512:
3292 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00003293 case X86::BI__builtin_ia32_cvtsi2sd64:
3294 case X86::BI__builtin_ia32_cvtsi2ss32:
3295 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00003296 case X86::BI__builtin_ia32_cvtusi2sd64:
3297 case X86::BI__builtin_ia32_cvtusi2ss32:
3298 case X86::BI__builtin_ia32_cvtusi2ss64:
3299 ArgNum = 2;
3300 HasRC = true;
3301 break;
3302 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3303 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3304 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3305 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3306 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3307 case X86::BI__builtin_ia32_cvtps2qq512_mask:
3308 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3309 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3310 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3311 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3312 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3313 ArgNum = 3;
3314 HasRC = true;
3315 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003316 case X86::BI__builtin_ia32_addss_round_mask:
3317 case X86::BI__builtin_ia32_addsd_round_mask:
3318 case X86::BI__builtin_ia32_divss_round_mask:
3319 case X86::BI__builtin_ia32_divsd_round_mask:
3320 case X86::BI__builtin_ia32_mulss_round_mask:
3321 case X86::BI__builtin_ia32_mulsd_round_mask:
3322 case X86::BI__builtin_ia32_subss_round_mask:
3323 case X86::BI__builtin_ia32_subsd_round_mask:
3324 case X86::BI__builtin_ia32_scalefpd512_mask:
3325 case X86::BI__builtin_ia32_scalefps512_mask:
3326 case X86::BI__builtin_ia32_scalefsd_round_mask:
3327 case X86::BI__builtin_ia32_scalefss_round_mask:
3328 case X86::BI__builtin_ia32_getmantpd512_mask:
3329 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003330 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3331 case X86::BI__builtin_ia32_sqrtsd_round_mask:
3332 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003333 case X86::BI__builtin_ia32_vfmaddsd3_mask:
3334 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3335 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3336 case X86::BI__builtin_ia32_vfmaddss3_mask:
3337 case X86::BI__builtin_ia32_vfmaddss3_maskz:
3338 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00003339 case X86::BI__builtin_ia32_vfmaddpd512_mask:
3340 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3341 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3342 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3343 case X86::BI__builtin_ia32_vfmaddps512_mask:
3344 case X86::BI__builtin_ia32_vfmaddps512_maskz:
3345 case X86::BI__builtin_ia32_vfmaddps512_mask3:
3346 case X86::BI__builtin_ia32_vfmsubps512_mask3:
3347 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3348 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3349 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3350 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3351 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3352 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3353 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3354 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00003355 ArgNum = 4;
3356 HasRC = true;
3357 break;
3358 case X86::BI__builtin_ia32_getmantsd_round_mask:
3359 case X86::BI__builtin_ia32_getmantss_round_mask:
3360 ArgNum = 5;
3361 HasRC = true;
3362 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003363 }
3364
3365 llvm::APSInt Result;
3366
3367 // We can't check the value of a dependent argument.
3368 Expr *Arg = TheCall->getArg(ArgNum);
3369 if (Arg->isTypeDependent() || Arg->isValueDependent())
3370 return false;
3371
3372 // Check constant-ness first.
3373 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3374 return true;
3375
3376 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3377 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3378 // combined with ROUND_NO_EXC.
3379 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3380 Result == 8/*ROUND_NO_EXC*/ ||
3381 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3382 return false;
3383
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003384 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3385 << Arg->getSourceRange();
Craig Toppera7e253e2016-09-23 04:48:31 +00003386}
3387
Craig Topperdf5beb22017-03-13 17:16:50 +00003388// Check if the gather/scatter scale is legal.
3389bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3390 CallExpr *TheCall) {
3391 unsigned ArgNum = 0;
3392 switch (BuiltinID) {
3393 default:
3394 return false;
3395 case X86::BI__builtin_ia32_gatherpfdpd:
3396 case X86::BI__builtin_ia32_gatherpfdps:
3397 case X86::BI__builtin_ia32_gatherpfqpd:
3398 case X86::BI__builtin_ia32_gatherpfqps:
3399 case X86::BI__builtin_ia32_scatterpfdpd:
3400 case X86::BI__builtin_ia32_scatterpfdps:
3401 case X86::BI__builtin_ia32_scatterpfqpd:
3402 case X86::BI__builtin_ia32_scatterpfqps:
3403 ArgNum = 3;
3404 break;
3405 case X86::BI__builtin_ia32_gatherd_pd:
3406 case X86::BI__builtin_ia32_gatherd_pd256:
3407 case X86::BI__builtin_ia32_gatherq_pd:
3408 case X86::BI__builtin_ia32_gatherq_pd256:
3409 case X86::BI__builtin_ia32_gatherd_ps:
3410 case X86::BI__builtin_ia32_gatherd_ps256:
3411 case X86::BI__builtin_ia32_gatherq_ps:
3412 case X86::BI__builtin_ia32_gatherq_ps256:
3413 case X86::BI__builtin_ia32_gatherd_q:
3414 case X86::BI__builtin_ia32_gatherd_q256:
3415 case X86::BI__builtin_ia32_gatherq_q:
3416 case X86::BI__builtin_ia32_gatherq_q256:
3417 case X86::BI__builtin_ia32_gatherd_d:
3418 case X86::BI__builtin_ia32_gatherd_d256:
3419 case X86::BI__builtin_ia32_gatherq_d:
3420 case X86::BI__builtin_ia32_gatherq_d256:
3421 case X86::BI__builtin_ia32_gather3div2df:
3422 case X86::BI__builtin_ia32_gather3div2di:
3423 case X86::BI__builtin_ia32_gather3div4df:
3424 case X86::BI__builtin_ia32_gather3div4di:
3425 case X86::BI__builtin_ia32_gather3div4sf:
3426 case X86::BI__builtin_ia32_gather3div4si:
3427 case X86::BI__builtin_ia32_gather3div8sf:
3428 case X86::BI__builtin_ia32_gather3div8si:
3429 case X86::BI__builtin_ia32_gather3siv2df:
3430 case X86::BI__builtin_ia32_gather3siv2di:
3431 case X86::BI__builtin_ia32_gather3siv4df:
3432 case X86::BI__builtin_ia32_gather3siv4di:
3433 case X86::BI__builtin_ia32_gather3siv4sf:
3434 case X86::BI__builtin_ia32_gather3siv4si:
3435 case X86::BI__builtin_ia32_gather3siv8sf:
3436 case X86::BI__builtin_ia32_gather3siv8si:
3437 case X86::BI__builtin_ia32_gathersiv8df:
3438 case X86::BI__builtin_ia32_gathersiv16sf:
3439 case X86::BI__builtin_ia32_gatherdiv8df:
3440 case X86::BI__builtin_ia32_gatherdiv16sf:
3441 case X86::BI__builtin_ia32_gathersiv8di:
3442 case X86::BI__builtin_ia32_gathersiv16si:
3443 case X86::BI__builtin_ia32_gatherdiv8di:
3444 case X86::BI__builtin_ia32_gatherdiv16si:
3445 case X86::BI__builtin_ia32_scatterdiv2df:
3446 case X86::BI__builtin_ia32_scatterdiv2di:
3447 case X86::BI__builtin_ia32_scatterdiv4df:
3448 case X86::BI__builtin_ia32_scatterdiv4di:
3449 case X86::BI__builtin_ia32_scatterdiv4sf:
3450 case X86::BI__builtin_ia32_scatterdiv4si:
3451 case X86::BI__builtin_ia32_scatterdiv8sf:
3452 case X86::BI__builtin_ia32_scatterdiv8si:
3453 case X86::BI__builtin_ia32_scattersiv2df:
3454 case X86::BI__builtin_ia32_scattersiv2di:
3455 case X86::BI__builtin_ia32_scattersiv4df:
3456 case X86::BI__builtin_ia32_scattersiv4di:
3457 case X86::BI__builtin_ia32_scattersiv4sf:
3458 case X86::BI__builtin_ia32_scattersiv4si:
3459 case X86::BI__builtin_ia32_scattersiv8sf:
3460 case X86::BI__builtin_ia32_scattersiv8si:
3461 case X86::BI__builtin_ia32_scattersiv8df:
3462 case X86::BI__builtin_ia32_scattersiv16sf:
3463 case X86::BI__builtin_ia32_scatterdiv8df:
3464 case X86::BI__builtin_ia32_scatterdiv16sf:
3465 case X86::BI__builtin_ia32_scattersiv8di:
3466 case X86::BI__builtin_ia32_scattersiv16si:
3467 case X86::BI__builtin_ia32_scatterdiv8di:
3468 case X86::BI__builtin_ia32_scatterdiv16si:
3469 ArgNum = 4;
3470 break;
3471 }
3472
3473 llvm::APSInt Result;
3474
3475 // We can't check the value of a dependent argument.
3476 Expr *Arg = TheCall->getArg(ArgNum);
3477 if (Arg->isTypeDependent() || Arg->isValueDependent())
3478 return false;
3479
3480 // Check constant-ness first.
3481 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3482 return true;
3483
3484 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3485 return false;
3486
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003487 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3488 << Arg->getSourceRange();
Craig Topperdf5beb22017-03-13 17:16:50 +00003489}
3490
Craig Topper51738f82018-04-26 20:14:46 +00003491static bool isX86_32Builtin(unsigned BuiltinID) {
3492 // These builtins only work on x86-32 targets.
3493 switch (BuiltinID) {
3494 case X86::BI__builtin_ia32_readeflags_u32:
3495 case X86::BI__builtin_ia32_writeeflags_u32:
3496 return true;
3497 }
3498
3499 return false;
3500}
3501
Craig Topperf0ddc892016-09-23 04:48:27 +00003502bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3503 if (BuiltinID == X86::BI__builtin_cpu_supports)
3504 return SemaBuiltinCpuSupports(*this, TheCall);
3505
Craig Topper699ae0c2017-08-10 20:28:30 +00003506 if (BuiltinID == X86::BI__builtin_cpu_is)
3507 return SemaBuiltinCpuIs(*this, TheCall);
3508
Craig Topper51738f82018-04-26 20:14:46 +00003509 // Check for 32-bit only builtins on a 64-bit target.
3510 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3511 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003512 return Diag(TheCall->getCallee()->getBeginLoc(),
Craig Topper51738f82018-04-26 20:14:46 +00003513 diag::err_32_bit_builtin_64_bit_tgt);
3514
Craig Toppera7e253e2016-09-23 04:48:31 +00003515 // If the intrinsic has rounding or SAE make sure its valid.
3516 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3517 return true;
3518
Craig Topperdf5beb22017-03-13 17:16:50 +00003519 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3520 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3521 return true;
3522
Craig Topperf0ddc892016-09-23 04:48:27 +00003523 // For intrinsics which take an immediate value as part of the instruction,
3524 // range check them here.
3525 int i = 0, l = 0, u = 0;
3526 switch (BuiltinID) {
3527 default:
3528 return false;
Craig Topper11899b02018-06-05 21:54:35 +00003529 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00003530 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003531 case X86::BI__builtin_ia32_vextractf128_pd256:
3532 case X86::BI__builtin_ia32_vextractf128_ps256:
3533 case X86::BI__builtin_ia32_vextractf128_si256:
3534 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00003535 case X86::BI__builtin_ia32_extractf64x4_mask:
3536 case X86::BI__builtin_ia32_extracti64x4_mask:
3537 case X86::BI__builtin_ia32_extractf32x8_mask:
3538 case X86::BI__builtin_ia32_extracti32x8_mask:
3539 case X86::BI__builtin_ia32_extractf64x2_256_mask:
3540 case X86::BI__builtin_ia32_extracti64x2_256_mask:
3541 case X86::BI__builtin_ia32_extractf32x4_256_mask:
3542 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003543 i = 1; l = 0; u = 1;
3544 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003545 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003546 case X86::BI__builtin_ia32_vinsertf128_pd256:
3547 case X86::BI__builtin_ia32_vinsertf128_ps256:
3548 case X86::BI__builtin_ia32_vinsertf128_si256:
3549 case X86::BI__builtin_ia32_insert128i256:
3550 case X86::BI__builtin_ia32_insertf32x8:
3551 case X86::BI__builtin_ia32_inserti32x8:
3552 case X86::BI__builtin_ia32_insertf64x4:
3553 case X86::BI__builtin_ia32_inserti64x4:
3554 case X86::BI__builtin_ia32_insertf64x2_256:
3555 case X86::BI__builtin_ia32_inserti64x2_256:
3556 case X86::BI__builtin_ia32_insertf32x4_256:
3557 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00003558 i = 2; l = 0; u = 1;
3559 break;
Craig Topperacf56012018-06-08 00:59:27 +00003560 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00003561 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003562 case X86::BI__builtin_ia32_vec_ext_v4si:
3563 case X86::BI__builtin_ia32_vec_ext_v4sf:
3564 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00003565 case X86::BI__builtin_ia32_extractf32x4_mask:
3566 case X86::BI__builtin_ia32_extracti32x4_mask:
3567 case X86::BI__builtin_ia32_extractf64x2_512_mask:
3568 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003569 i = 1; l = 0; u = 3;
3570 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003571 case X86::BI_mm_prefetch:
3572 case X86::BI__builtin_ia32_vec_ext_v8hi:
3573 case X86::BI__builtin_ia32_vec_ext_v8si:
3574 i = 1; l = 0; u = 7;
3575 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00003576 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00003577 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00003578 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00003579 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003580 case X86::BI__builtin_ia32_vec_set_v4si:
3581 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00003582 case X86::BI__builtin_ia32_shuf_f32x4_256:
3583 case X86::BI__builtin_ia32_shuf_f64x2_256:
3584 case X86::BI__builtin_ia32_shuf_i32x4_256:
3585 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00003586 case X86::BI__builtin_ia32_insertf64x2_512:
3587 case X86::BI__builtin_ia32_inserti64x2_512:
3588 case X86::BI__builtin_ia32_insertf32x4:
3589 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00003590 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003591 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00003592 case X86::BI__builtin_ia32_vpermil2pd:
3593 case X86::BI__builtin_ia32_vpermil2pd256:
3594 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00003595 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00003596 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003597 break;
Craig Topper95b0d732015-01-25 23:30:05 +00003598 case X86::BI__builtin_ia32_cmpb128_mask:
3599 case X86::BI__builtin_ia32_cmpw128_mask:
3600 case X86::BI__builtin_ia32_cmpd128_mask:
3601 case X86::BI__builtin_ia32_cmpq128_mask:
3602 case X86::BI__builtin_ia32_cmpb256_mask:
3603 case X86::BI__builtin_ia32_cmpw256_mask:
3604 case X86::BI__builtin_ia32_cmpd256_mask:
3605 case X86::BI__builtin_ia32_cmpq256_mask:
3606 case X86::BI__builtin_ia32_cmpb512_mask:
3607 case X86::BI__builtin_ia32_cmpw512_mask:
3608 case X86::BI__builtin_ia32_cmpd512_mask:
3609 case X86::BI__builtin_ia32_cmpq512_mask:
3610 case X86::BI__builtin_ia32_ucmpb128_mask:
3611 case X86::BI__builtin_ia32_ucmpw128_mask:
3612 case X86::BI__builtin_ia32_ucmpd128_mask:
3613 case X86::BI__builtin_ia32_ucmpq128_mask:
3614 case X86::BI__builtin_ia32_ucmpb256_mask:
3615 case X86::BI__builtin_ia32_ucmpw256_mask:
3616 case X86::BI__builtin_ia32_ucmpd256_mask:
3617 case X86::BI__builtin_ia32_ucmpq256_mask:
3618 case X86::BI__builtin_ia32_ucmpb512_mask:
3619 case X86::BI__builtin_ia32_ucmpw512_mask:
3620 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00003621 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00003622 case X86::BI__builtin_ia32_vpcomub:
3623 case X86::BI__builtin_ia32_vpcomuw:
3624 case X86::BI__builtin_ia32_vpcomud:
3625 case X86::BI__builtin_ia32_vpcomuq:
3626 case X86::BI__builtin_ia32_vpcomb:
3627 case X86::BI__builtin_ia32_vpcomw:
3628 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00003629 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00003630 case X86::BI__builtin_ia32_vec_set_v8hi:
3631 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00003632 i = 2; l = 0; u = 7;
3633 break;
Craig Topperacf56012018-06-08 00:59:27 +00003634 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003635 case X86::BI__builtin_ia32_roundps:
3636 case X86::BI__builtin_ia32_roundpd:
3637 case X86::BI__builtin_ia32_roundps256:
3638 case X86::BI__builtin_ia32_roundpd256:
Craig Topper03a1d482018-06-15 17:03:32 +00003639 case X86::BI__builtin_ia32_getmantpd128_mask:
3640 case X86::BI__builtin_ia32_getmantpd256_mask:
3641 case X86::BI__builtin_ia32_getmantps128_mask:
3642 case X86::BI__builtin_ia32_getmantps256_mask:
3643 case X86::BI__builtin_ia32_getmantpd512_mask:
3644 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003645 case X86::BI__builtin_ia32_vec_ext_v16qi:
3646 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003647 i = 1; l = 0; u = 15;
3648 break;
Craig Topper7d17d722018-06-08 00:00:21 +00003649 case X86::BI__builtin_ia32_pblendd128:
3650 case X86::BI__builtin_ia32_blendps:
3651 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00003652 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003653 case X86::BI__builtin_ia32_roundss:
3654 case X86::BI__builtin_ia32_roundsd:
3655 case X86::BI__builtin_ia32_rangepd128_mask:
3656 case X86::BI__builtin_ia32_rangepd256_mask:
3657 case X86::BI__builtin_ia32_rangepd512_mask:
3658 case X86::BI__builtin_ia32_rangeps128_mask:
3659 case X86::BI__builtin_ia32_rangeps256_mask:
3660 case X86::BI__builtin_ia32_rangeps512_mask:
3661 case X86::BI__builtin_ia32_getmantsd_round_mask:
3662 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003663 case X86::BI__builtin_ia32_vec_set_v16qi:
3664 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003665 i = 2; l = 0; u = 15;
3666 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003667 case X86::BI__builtin_ia32_vec_ext_v32qi:
3668 i = 1; l = 0; u = 31;
3669 break;
Craig Topper39c87102016-05-18 03:18:12 +00003670 case X86::BI__builtin_ia32_cmpps:
3671 case X86::BI__builtin_ia32_cmpss:
3672 case X86::BI__builtin_ia32_cmppd:
3673 case X86::BI__builtin_ia32_cmpsd:
3674 case X86::BI__builtin_ia32_cmpps256:
3675 case X86::BI__builtin_ia32_cmppd256:
3676 case X86::BI__builtin_ia32_cmpps128_mask:
3677 case X86::BI__builtin_ia32_cmppd128_mask:
3678 case X86::BI__builtin_ia32_cmpps256_mask:
3679 case X86::BI__builtin_ia32_cmppd256_mask:
3680 case X86::BI__builtin_ia32_cmpps512_mask:
3681 case X86::BI__builtin_ia32_cmppd512_mask:
3682 case X86::BI__builtin_ia32_cmpsd_mask:
3683 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003684 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00003685 i = 2; l = 0; u = 31;
3686 break;
Craig Topper03f4f042018-06-08 18:00:25 +00003687 case X86::BI__builtin_ia32_permdf256:
3688 case X86::BI__builtin_ia32_permdi256:
3689 case X86::BI__builtin_ia32_permdf512:
3690 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00003691 case X86::BI__builtin_ia32_vpermilps:
3692 case X86::BI__builtin_ia32_vpermilps256:
3693 case X86::BI__builtin_ia32_vpermilpd512:
3694 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00003695 case X86::BI__builtin_ia32_pshufd:
3696 case X86::BI__builtin_ia32_pshufd256:
3697 case X86::BI__builtin_ia32_pshufd512:
3698 case X86::BI__builtin_ia32_pshufhw:
3699 case X86::BI__builtin_ia32_pshufhw256:
3700 case X86::BI__builtin_ia32_pshufhw512:
3701 case X86::BI__builtin_ia32_pshuflw:
3702 case X86::BI__builtin_ia32_pshuflw256:
3703 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00003704 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00003705 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003706 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00003707 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3708 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003709 case X86::BI__builtin_ia32_rndscaleps_128_mask:
3710 case X86::BI__builtin_ia32_rndscalepd_128_mask:
3711 case X86::BI__builtin_ia32_rndscaleps_256_mask:
3712 case X86::BI__builtin_ia32_rndscalepd_256_mask:
3713 case X86::BI__builtin_ia32_rndscaleps_mask:
3714 case X86::BI__builtin_ia32_rndscalepd_mask:
3715 case X86::BI__builtin_ia32_reducepd128_mask:
3716 case X86::BI__builtin_ia32_reducepd256_mask:
3717 case X86::BI__builtin_ia32_reducepd512_mask:
3718 case X86::BI__builtin_ia32_reduceps128_mask:
3719 case X86::BI__builtin_ia32_reduceps256_mask:
3720 case X86::BI__builtin_ia32_reduceps512_mask:
Craig Topper0e9de762018-06-30 01:32:14 +00003721 case X86::BI__builtin_ia32_prold512:
3722 case X86::BI__builtin_ia32_prolq512:
3723 case X86::BI__builtin_ia32_prold128:
3724 case X86::BI__builtin_ia32_prold256:
3725 case X86::BI__builtin_ia32_prolq128:
3726 case X86::BI__builtin_ia32_prolq256:
3727 case X86::BI__builtin_ia32_prord512:
3728 case X86::BI__builtin_ia32_prorq512:
3729 case X86::BI__builtin_ia32_prord128:
3730 case X86::BI__builtin_ia32_prord256:
3731 case X86::BI__builtin_ia32_prorq128:
3732 case X86::BI__builtin_ia32_prorq256:
Craig Topper39c87102016-05-18 03:18:12 +00003733 case X86::BI__builtin_ia32_fpclasspd128_mask:
3734 case X86::BI__builtin_ia32_fpclasspd256_mask:
3735 case X86::BI__builtin_ia32_fpclassps128_mask:
3736 case X86::BI__builtin_ia32_fpclassps256_mask:
3737 case X86::BI__builtin_ia32_fpclassps512_mask:
3738 case X86::BI__builtin_ia32_fpclasspd512_mask:
3739 case X86::BI__builtin_ia32_fpclasssd_mask:
3740 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00003741 case X86::BI__builtin_ia32_pslldqi128_byteshift:
3742 case X86::BI__builtin_ia32_pslldqi256_byteshift:
3743 case X86::BI__builtin_ia32_pslldqi512_byteshift:
3744 case X86::BI__builtin_ia32_psrldqi128_byteshift:
3745 case X86::BI__builtin_ia32_psrldqi256_byteshift:
3746 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper2aa8efc2018-08-31 18:22:52 +00003747 case X86::BI__builtin_ia32_kshiftliqi:
3748 case X86::BI__builtin_ia32_kshiftlihi:
3749 case X86::BI__builtin_ia32_kshiftlisi:
3750 case X86::BI__builtin_ia32_kshiftlidi:
3751 case X86::BI__builtin_ia32_kshiftriqi:
3752 case X86::BI__builtin_ia32_kshiftrihi:
3753 case X86::BI__builtin_ia32_kshiftrisi:
3754 case X86::BI__builtin_ia32_kshiftridi:
Craig Topper39c87102016-05-18 03:18:12 +00003755 i = 1; l = 0; u = 255;
3756 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00003757 case X86::BI__builtin_ia32_vperm2f128_pd256:
3758 case X86::BI__builtin_ia32_vperm2f128_ps256:
3759 case X86::BI__builtin_ia32_vperm2f128_si256:
3760 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00003761 case X86::BI__builtin_ia32_pblendw128:
3762 case X86::BI__builtin_ia32_pblendw256:
3763 case X86::BI__builtin_ia32_blendps256:
3764 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00003765 case X86::BI__builtin_ia32_palignr128:
3766 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00003767 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00003768 case X86::BI__builtin_ia32_alignq512:
3769 case X86::BI__builtin_ia32_alignd512:
3770 case X86::BI__builtin_ia32_alignd128:
3771 case X86::BI__builtin_ia32_alignd256:
3772 case X86::BI__builtin_ia32_alignq128:
3773 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00003774 case X86::BI__builtin_ia32_vcomisd:
3775 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00003776 case X86::BI__builtin_ia32_shuf_f32x4:
3777 case X86::BI__builtin_ia32_shuf_f64x2:
3778 case X86::BI__builtin_ia32_shuf_i32x4:
3779 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00003780 case X86::BI__builtin_ia32_shufpd512:
3781 case X86::BI__builtin_ia32_shufps:
3782 case X86::BI__builtin_ia32_shufps256:
3783 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00003784 case X86::BI__builtin_ia32_dbpsadbw128:
3785 case X86::BI__builtin_ia32_dbpsadbw256:
3786 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00003787 case X86::BI__builtin_ia32_vpshldd128:
3788 case X86::BI__builtin_ia32_vpshldd256:
3789 case X86::BI__builtin_ia32_vpshldd512:
3790 case X86::BI__builtin_ia32_vpshldq128:
3791 case X86::BI__builtin_ia32_vpshldq256:
3792 case X86::BI__builtin_ia32_vpshldq512:
3793 case X86::BI__builtin_ia32_vpshldw128:
3794 case X86::BI__builtin_ia32_vpshldw256:
3795 case X86::BI__builtin_ia32_vpshldw512:
3796 case X86::BI__builtin_ia32_vpshrdd128:
3797 case X86::BI__builtin_ia32_vpshrdd256:
3798 case X86::BI__builtin_ia32_vpshrdd512:
3799 case X86::BI__builtin_ia32_vpshrdq128:
3800 case X86::BI__builtin_ia32_vpshrdq256:
3801 case X86::BI__builtin_ia32_vpshrdq512:
3802 case X86::BI__builtin_ia32_vpshrdw128:
3803 case X86::BI__builtin_ia32_vpshrdw256:
3804 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00003805 i = 2; l = 0; u = 255;
3806 break;
3807 case X86::BI__builtin_ia32_fixupimmpd512_mask:
3808 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3809 case X86::BI__builtin_ia32_fixupimmps512_mask:
3810 case X86::BI__builtin_ia32_fixupimmps512_maskz:
3811 case X86::BI__builtin_ia32_fixupimmsd_mask:
3812 case X86::BI__builtin_ia32_fixupimmsd_maskz:
3813 case X86::BI__builtin_ia32_fixupimmss_mask:
3814 case X86::BI__builtin_ia32_fixupimmss_maskz:
3815 case X86::BI__builtin_ia32_fixupimmpd128_mask:
3816 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3817 case X86::BI__builtin_ia32_fixupimmpd256_mask:
3818 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3819 case X86::BI__builtin_ia32_fixupimmps128_mask:
3820 case X86::BI__builtin_ia32_fixupimmps128_maskz:
3821 case X86::BI__builtin_ia32_fixupimmps256_mask:
3822 case X86::BI__builtin_ia32_fixupimmps256_maskz:
3823 case X86::BI__builtin_ia32_pternlogd512_mask:
3824 case X86::BI__builtin_ia32_pternlogd512_maskz:
3825 case X86::BI__builtin_ia32_pternlogq512_mask:
3826 case X86::BI__builtin_ia32_pternlogq512_maskz:
3827 case X86::BI__builtin_ia32_pternlogd128_mask:
3828 case X86::BI__builtin_ia32_pternlogd128_maskz:
3829 case X86::BI__builtin_ia32_pternlogd256_mask:
3830 case X86::BI__builtin_ia32_pternlogd256_maskz:
3831 case X86::BI__builtin_ia32_pternlogq128_mask:
3832 case X86::BI__builtin_ia32_pternlogq128_maskz:
3833 case X86::BI__builtin_ia32_pternlogq256_mask:
3834 case X86::BI__builtin_ia32_pternlogq256_maskz:
3835 i = 3; l = 0; u = 255;
3836 break;
Craig Topper9625db02017-03-12 22:19:10 +00003837 case X86::BI__builtin_ia32_gatherpfdpd:
3838 case X86::BI__builtin_ia32_gatherpfdps:
3839 case X86::BI__builtin_ia32_gatherpfqpd:
3840 case X86::BI__builtin_ia32_gatherpfqps:
3841 case X86::BI__builtin_ia32_scatterpfdpd:
3842 case X86::BI__builtin_ia32_scatterpfdps:
3843 case X86::BI__builtin_ia32_scatterpfqpd:
3844 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00003845 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00003846 break;
Craig Topper39c87102016-05-18 03:18:12 +00003847 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3848 case X86::BI__builtin_ia32_rndscaless_round_mask:
3849 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00003850 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003851 }
Chandler Carruth16e6bc22018-06-21 23:46:09 +00003852
3853 // Note that we don't force a hard error on the range check here, allowing
3854 // template-generated or macro-generated dead code to potentially have out-of-
3855 // range values. These need to code generate, but don't need to necessarily
3856 // make any sense. We use a warning that defaults to an error.
3857 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003858}
3859
Richard Smith55ce3522012-06-25 20:30:08 +00003860/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3861/// parameter with the FormatAttr's correct format_idx and firstDataArg.
3862/// Returns true when the format fits the function and the FormatStringInfo has
3863/// been populated.
3864bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3865 FormatStringInfo *FSI) {
3866 FSI->HasVAListArg = Format->getFirstArg() == 0;
3867 FSI->FormatIdx = Format->getFormatIdx() - 1;
3868 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003869
Richard Smith55ce3522012-06-25 20:30:08 +00003870 // The way the format attribute works in GCC, the implicit this argument
3871 // of member functions is counted. However, it doesn't appear in our own
3872 // lists, so decrement format_idx in that case.
3873 if (IsCXXMember) {
3874 if(FSI->FormatIdx == 0)
3875 return false;
3876 --FSI->FormatIdx;
3877 if (FSI->FirstDataArg != 0)
3878 --FSI->FirstDataArg;
3879 }
3880 return true;
3881}
Mike Stump11289f42009-09-09 15:08:12 +00003882
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003883/// Checks if a the given expression evaluates to null.
3884///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003885/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00003886static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003887 // If the expression has non-null type, it doesn't evaluate to null.
3888 if (auto nullability
3889 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3890 if (*nullability == NullabilityKind::NonNull)
3891 return false;
3892 }
3893
Ted Kremeneka146db32014-01-17 06:24:47 +00003894 // As a special case, transparent unions initialized with zero are
3895 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003896 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00003897 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3898 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003899 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00003900 if (const InitListExpr *ILE =
3901 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003902 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00003903 }
3904
3905 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00003906 return (!Expr->isValueDependent() &&
3907 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3908 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003909}
3910
3911static void CheckNonNullArgument(Sema &S,
3912 const Expr *ArgExpr,
3913 SourceLocation CallSiteLoc) {
3914 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00003915 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3916 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00003917}
3918
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003919bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3920 FormatStringInfo FSI;
3921 if ((GetFormatStringType(Format) == FST_NSString) &&
3922 getFormatStringInfo(Format, false, &FSI)) {
3923 Idx = FSI.FormatIdx;
3924 return true;
3925 }
3926 return false;
3927}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003928
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003929/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003930/// as formatting string to formatting method.
3931static void
3932DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3933 const NamedDecl *FDecl,
3934 Expr **Args,
3935 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003936 unsigned Idx = 0;
3937 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003938 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3939 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003940 Idx = 2;
3941 Format = true;
3942 }
3943 else
3944 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3945 if (S.GetFormatNSStringIdx(I, Idx)) {
3946 Format = true;
3947 break;
3948 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003949 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003950 if (!Format || NumArgs <= Idx)
3951 return;
3952 const Expr *FormatExpr = Args[Idx];
3953 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3954 FormatExpr = CSCE->getSubExpr();
3955 const StringLiteral *FormatString;
3956 if (const ObjCStringLiteral *OSL =
3957 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3958 FormatString = OSL->getString();
3959 else
3960 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3961 if (!FormatString)
3962 return;
3963 if (S.FormatStringHasSArg(FormatString)) {
3964 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3965 << "%s" << 1 << 1;
3966 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3967 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003968 }
3969}
3970
Douglas Gregorb4866e82015-06-19 18:13:19 +00003971/// Determine whether the given type has a non-null nullability annotation.
3972static bool isNonNullType(ASTContext &ctx, QualType type) {
3973 if (auto nullability = type->getNullability(ctx))
3974 return *nullability == NullabilityKind::NonNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003975
Douglas Gregorb4866e82015-06-19 18:13:19 +00003976 return false;
3977}
3978
Ted Kremenek2bc73332014-01-17 06:24:43 +00003979static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00003980 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003981 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00003982 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00003983 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003984 assert((FDecl || Proto) && "Need a function declaration or prototype");
3985
Ted Kremenek9aedc152014-01-17 06:24:56 +00003986 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00003987 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00003988 if (FDecl) {
3989 // Handle the nonnull attribute on the function/method declaration itself.
3990 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3991 if (!NonNull->args_size()) {
3992 // Easy case: all pointer arguments are nonnull.
3993 for (const auto *Arg : Args)
3994 if (S.isValidPointerAttrType(Arg->getType()))
3995 CheckNonNullArgument(S, Arg, CallSiteLoc);
3996 return;
3997 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003998
Joel E. Denny81508102018-03-13 14:51:22 +00003999 for (const ParamIdx &Idx : NonNull->args()) {
4000 unsigned IdxAST = Idx.getASTIndex();
4001 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00004002 continue;
4003 if (NonNullArgs.empty())
4004 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00004005 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004006 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004007 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004008 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004009
Douglas Gregorb4866e82015-06-19 18:13:19 +00004010 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4011 // Handle the nonnull attribute on the parameters of the
4012 // function/method.
4013 ArrayRef<ParmVarDecl*> parms;
4014 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4015 parms = FD->parameters();
4016 else
4017 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
Fangrui Song6907ce22018-07-30 19:24:48 +00004018
Douglas Gregorb4866e82015-06-19 18:13:19 +00004019 unsigned ParamIndex = 0;
4020 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4021 I != E; ++I, ++ParamIndex) {
4022 const ParmVarDecl *PVD = *I;
Fangrui Song6907ce22018-07-30 19:24:48 +00004023 if (PVD->hasAttr<NonNullAttr>() ||
Douglas Gregorb4866e82015-06-19 18:13:19 +00004024 isNonNullType(S.Context, PVD->getType())) {
4025 if (NonNullArgs.empty())
4026 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00004027
Douglas Gregorb4866e82015-06-19 18:13:19 +00004028 NonNullArgs.set(ParamIndex);
4029 }
4030 }
4031 } else {
4032 // If we have a non-function, non-method declaration but no
4033 // function prototype, try to dig out the function prototype.
4034 if (!Proto) {
4035 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4036 QualType type = VD->getType().getNonReferenceType();
4037 if (auto pointerType = type->getAs<PointerType>())
4038 type = pointerType->getPointeeType();
4039 else if (auto blockType = type->getAs<BlockPointerType>())
4040 type = blockType->getPointeeType();
4041 // FIXME: data member pointers?
4042
4043 // Dig out the function prototype, if there is one.
4044 Proto = type->getAs<FunctionProtoType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004045 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00004046 }
4047
4048 // Fill in non-null argument information from the nullability
4049 // information on the parameter types (if we have them).
4050 if (Proto) {
4051 unsigned Index = 0;
4052 for (auto paramType : Proto->getParamTypes()) {
4053 if (isNonNullType(S.Context, paramType)) {
4054 if (NonNullArgs.empty())
4055 NonNullArgs.resize(Args.size());
Fangrui Song6907ce22018-07-30 19:24:48 +00004056
Douglas Gregorb4866e82015-06-19 18:13:19 +00004057 NonNullArgs.set(Index);
4058 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004059
Douglas Gregorb4866e82015-06-19 18:13:19 +00004060 ++Index;
4061 }
4062 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004063 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004064
Douglas Gregorb4866e82015-06-19 18:13:19 +00004065 // Check for non-null arguments.
Fangrui Song6907ce22018-07-30 19:24:48 +00004066 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
Douglas Gregorb4866e82015-06-19 18:13:19 +00004067 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00004068 if (NonNullArgs[ArgIndex])
4069 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004070 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004071}
4072
Richard Smith55ce3522012-06-25 20:30:08 +00004073/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00004074/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4075/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004076void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00004077 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4078 bool IsMemberFunction, SourceLocation Loc,
4079 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00004080 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00004081 if (CurContext->isDependentContext())
4082 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00004083
Ted Kremenekb8176da2010-09-09 04:33:05 +00004084 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00004085 llvm::SmallBitVector CheckedVarArgs;
4086 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004087 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004088 // Only create vector if there are format attributes.
4089 CheckedVarArgs.resize(Args.size());
4090
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004091 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00004092 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004093 }
Richard Smithd7293d72013-08-05 18:49:43 +00004094 }
Richard Smith55ce3522012-06-25 20:30:08 +00004095
4096 // Refuse POD arguments that weren't caught by the format string
4097 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00004098 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4099 if (CallType != VariadicDoesNotApply &&
4100 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004101 unsigned NumParams = Proto ? Proto->getNumParams()
4102 : FDecl && isa<FunctionDecl>(FDecl)
4103 ? cast<FunctionDecl>(FDecl)->getNumParams()
4104 : FDecl && isa<ObjCMethodDecl>(FDecl)
4105 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4106 : 0;
4107
Alp Toker9cacbab2014-01-20 20:26:09 +00004108 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004109 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00004110 if (const Expr *Arg = Args[ArgIdx]) {
4111 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4112 checkVariadicArgument(Arg, CallType);
4113 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004114 }
Richard Smithd7293d72013-08-05 18:49:43 +00004115 }
Mike Stump11289f42009-09-09 15:08:12 +00004116
Douglas Gregorb4866e82015-06-19 18:13:19 +00004117 if (FDecl || Proto) {
4118 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004119
Richard Trieu41bc0992013-06-22 00:20:41 +00004120 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004121 if (FDecl) {
4122 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00004123 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004124 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004125 }
George Burgess IVce6284b2017-01-28 02:19:40 +00004126
4127 if (FD)
4128 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00004129}
4130
4131/// CheckConstructorCall - Check a constructor call for correctness and safety
4132/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004133void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4134 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004135 const FunctionProtoType *Proto,
4136 SourceLocation Loc) {
4137 VariadicCallType CallType =
4138 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00004139 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4140 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00004141}
4142
4143/// CheckFunctionCall - Check a direct function call for various correctness
4144/// and safety properties not strictly enforced by the C type system.
4145bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4146 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004147 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4148 isa<CXXMethodDecl>(FDecl);
4149 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4150 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00004151 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4152 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00004153 Expr** Args = TheCall->getArgs();
4154 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00004155
4156 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00004157 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004158 // If this is a call to a member operator, hide the first argument
4159 // from checkCall.
4160 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00004161 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00004162 ++Args;
4163 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00004164 } else if (IsMemberFunction)
4165 ImplicitThis =
4166 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4167
4168 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00004169 IsMemberFunction, TheCall->getRParenLoc(),
4170 TheCall->getCallee()->getSourceRange(), CallType);
4171
4172 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4173 // None of the checks below are needed for functions that don't have
4174 // simple names (e.g., C++ conversion functions).
4175 if (!FnInfo)
4176 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004177
Richard Trieua7f30b12016-12-06 01:42:28 +00004178 CheckAbsoluteValueFunction(TheCall, FDecl);
4179 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00004180
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004181 if (getLangOpts().ObjC)
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004182 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004183
Anna Zaks22122702012-01-17 00:37:07 +00004184 unsigned CMId = FDecl->getMemoryFunctionKind();
4185 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00004186 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00004187
Anna Zaks201d4892012-01-13 21:52:01 +00004188 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00004189 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00004190 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00004191 else if (CMId == Builtin::BIstrncat)
4192 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00004193 else
Anna Zaks22122702012-01-17 00:37:07 +00004194 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004195
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004196 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00004197}
4198
Fangrui Song6907ce22018-07-30 19:24:48 +00004199bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00004200 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00004201 VariadicCallType CallType =
4202 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004203
George Burgess IVce6284b2017-01-28 02:19:40 +00004204 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4205 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004206 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004207
4208 return false;
4209}
4210
Richard Trieu664c4c62013-06-20 21:03:13 +00004211bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4212 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00004213 QualType Ty;
4214 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004215 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004216 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004217 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004218 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004219 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004220
Douglas Gregorb4866e82015-06-19 18:13:19 +00004221 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4222 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004223 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004224
Richard Trieu664c4c62013-06-20 21:03:13 +00004225 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00004226 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00004227 CallType = VariadicDoesNotApply;
4228 } else if (Ty->isBlockPointerType()) {
4229 CallType = VariadicBlock;
4230 } else { // Ty->isFunctionPointerType()
4231 CallType = VariadicFunction;
4232 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004233
George Burgess IVce6284b2017-01-28 02:19:40 +00004234 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004235 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4236 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00004237 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00004238
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004239 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00004240}
4241
Richard Trieu41bc0992013-06-22 00:20:41 +00004242/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4243/// such as function pointers returned from functions.
4244bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004245 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00004246 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00004247 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00004248 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004249 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00004250 TheCall->getCallee()->getSourceRange(), CallType);
4251
4252 return false;
4253}
4254
Tim Northovere94a34c2014-03-11 10:49:14 +00004255static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00004256 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00004257 return false;
4258
JF Bastiendda2cb12016-04-18 18:01:49 +00004259 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00004260 switch (Op) {
4261 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004262 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00004263 llvm_unreachable("There is no ordering argument for an init");
4264
4265 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004266 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00004267 case AtomicExpr::AO__atomic_load_n:
4268 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00004269 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4270 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004271
4272 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004273 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00004274 case AtomicExpr::AO__atomic_store:
4275 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00004276 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4277 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4278 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004279
4280 default:
4281 return true;
4282 }
4283}
4284
Richard Smithfeea8832012-04-12 05:08:17 +00004285ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4286 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004287 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4288 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004289
Yaxun Liu39195062017-08-04 18:16:31 +00004290 // All the non-OpenCL operations take one of the following forms.
4291 // The OpenCL operations take the __c11 forms with one extra argument for
4292 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00004293 enum {
4294 // C __c11_atomic_init(A *, C)
4295 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004296
Richard Smithfeea8832012-04-12 05:08:17 +00004297 // C __c11_atomic_load(A *, int)
4298 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004299
Richard Smithfeea8832012-04-12 05:08:17 +00004300 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00004301 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004302
Eric Fiselier8d662442016-03-30 23:39:56 +00004303 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00004304 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004305
Richard Smithfeea8832012-04-12 05:08:17 +00004306 // C __c11_atomic_add(A *, M, int)
4307 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004308
Richard Smithfeea8832012-04-12 05:08:17 +00004309 // C __atomic_exchange_n(A *, CP, int)
4310 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004311
Richard Smithfeea8832012-04-12 05:08:17 +00004312 // void __atomic_exchange(A *, C *, CP, int)
4313 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004314
Richard Smithfeea8832012-04-12 05:08:17 +00004315 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4316 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004317
Richard Smithfeea8832012-04-12 05:08:17 +00004318 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4319 GNUCmpXchg
4320 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004321
Yaxun Liu39195062017-08-04 18:16:31 +00004322 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00004323 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4324 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00004325 // where:
4326 // C is an appropriate type,
4327 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4328 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4329 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4330 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004331
Yaxun Liu39195062017-08-04 18:16:31 +00004332 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4333 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4334 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00004335 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4336 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4337 AtomicExpr::AO__atomic_load,
4338 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00004339 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4340 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4341 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4342 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4343 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00004344 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4345 Op == AtomicExpr::AO__atomic_store_n ||
4346 Op == AtomicExpr::AO__atomic_exchange_n ||
4347 Op == AtomicExpr::AO__atomic_compare_exchange_n;
4348 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004349 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00004350
4351 switch (Op) {
4352 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004353 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00004354 Form = Init;
4355 break;
4356
4357 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004358 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004359 case AtomicExpr::AO__atomic_load_n:
4360 Form = Load;
4361 break;
4362
Richard Smithfeea8832012-04-12 05:08:17 +00004363 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00004364 Form = LoadCopy;
4365 break;
4366
4367 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004368 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00004369 case AtomicExpr::AO__atomic_store:
4370 case AtomicExpr::AO__atomic_store_n:
4371 Form = Copy;
4372 break;
4373
4374 case AtomicExpr::AO__c11_atomic_fetch_add:
4375 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00004376 case AtomicExpr::AO__opencl_atomic_fetch_add:
4377 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4378 case AtomicExpr::AO__opencl_atomic_fetch_min:
4379 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004380 case AtomicExpr::AO__atomic_fetch_add:
4381 case AtomicExpr::AO__atomic_fetch_sub:
4382 case AtomicExpr::AO__atomic_add_fetch:
4383 case AtomicExpr::AO__atomic_sub_fetch:
4384 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00004385 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00004386 case AtomicExpr::AO__c11_atomic_fetch_and:
4387 case AtomicExpr::AO__c11_atomic_fetch_or:
4388 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00004389 case AtomicExpr::AO__opencl_atomic_fetch_and:
4390 case AtomicExpr::AO__opencl_atomic_fetch_or:
4391 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00004392 case AtomicExpr::AO__atomic_fetch_and:
4393 case AtomicExpr::AO__atomic_fetch_or:
4394 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004395 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004396 case AtomicExpr::AO__atomic_and_fetch:
4397 case AtomicExpr::AO__atomic_or_fetch:
4398 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004399 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00004400 Form = Arithmetic;
4401 break;
4402
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004403 case AtomicExpr::AO__atomic_fetch_min:
4404 case AtomicExpr::AO__atomic_fetch_max:
4405 IsMinMax = true;
4406 Form = Arithmetic;
4407 break;
4408
Richard Smithfeea8832012-04-12 05:08:17 +00004409 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00004410 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00004411 case AtomicExpr::AO__atomic_exchange_n:
4412 Form = Xchg;
4413 break;
4414
4415 case AtomicExpr::AO__atomic_exchange:
4416 Form = GNUXchg;
4417 break;
4418
4419 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4420 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00004421 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4422 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004423 Form = C11CmpXchg;
4424 break;
4425
4426 case AtomicExpr::AO__atomic_compare_exchange:
4427 case AtomicExpr::AO__atomic_compare_exchange_n:
4428 Form = GNUCmpXchg;
4429 break;
4430 }
4431
Yaxun Liu39195062017-08-04 18:16:31 +00004432 unsigned AdjustedNumArgs = NumArgs[Form];
4433 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4434 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00004435 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00004436 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004437 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4438 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4439 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004440 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00004441 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004442 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004443 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004444 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4445 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004446 return ExprError();
4447 }
4448
Richard Smithfeea8832012-04-12 05:08:17 +00004449 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004450 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00004451 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4452 if (ConvertedPtr.isInvalid())
4453 return ExprError();
4454
4455 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004456 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4457 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004458 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4459 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004460 return ExprError();
4461 }
4462
Richard Smithfeea8832012-04-12 05:08:17 +00004463 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4464 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4465 QualType ValType = AtomTy; // 'C'
4466 if (IsC11) {
4467 if (!AtomTy->isAtomicType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004468 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4469 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004470 return ExprError();
4471 }
JF Bastienb4b1f592018-08-02 17:35:46 +00004472 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
Yaxun Liu39195062017-08-04 18:16:31 +00004473 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004474 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00004475 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4476 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00004477 return ExprError();
4478 }
Richard Smithfeea8832012-04-12 05:08:17 +00004479 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00004480 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004481 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004482 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4483 << Ptr->getType() << Ptr->getSourceRange();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004484 return ExprError();
4485 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004486 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004487
Richard Smithfeea8832012-04-12 05:08:17 +00004488 // For an arithmetic operation, the implied arithmetic must be well-formed.
4489 if (Form == Arithmetic) {
4490 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004491 if (IsAddSub && !ValType->isIntegerType()
4492 && !ValType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004493 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4494 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004495 return ExprError();
4496 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004497 if (IsMinMax) {
4498 const BuiltinType *BT = ValType->getAs<BuiltinType>();
4499 if (!BT || (BT->getKind() != BuiltinType::Int &&
4500 BT->getKind() != BuiltinType::UInt)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004501 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004502 return ExprError();
4503 }
4504 }
4505 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004506 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4507 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004508 return ExprError();
4509 }
David Majnemere85cff82015-01-28 05:48:06 +00004510 if (IsC11 && ValType->isPointerType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004511 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
David Majnemere85cff82015-01-28 05:48:06 +00004512 diag::err_incomplete_type)) {
4513 return ExprError();
4514 }
Richard Smithfeea8832012-04-12 05:08:17 +00004515 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4516 // For __atomic_*_n operations, the value type must be a scalar integral or
4517 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004518 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4519 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004520 return ExprError();
4521 }
4522
Eli Friedmanaa769812013-09-11 03:49:34 +00004523 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4524 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00004525 // For GNU atomics, require a trivially-copyable type. This is not part of
4526 // the GNU atomics specification, but we enforce it for sanity.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004527 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4528 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004529 return ExprError();
4530 }
4531
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004532 switch (ValType.getObjCLifetime()) {
4533 case Qualifiers::OCL_None:
4534 case Qualifiers::OCL_ExplicitNone:
4535 // okay
4536 break;
4537
4538 case Qualifiers::OCL_Weak:
4539 case Qualifiers::OCL_Strong:
4540 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00004541 // FIXME: Can this happen? By this point, ValType should be known
4542 // to be trivially copyable.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004543 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4544 << ValType << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004545 return ExprError();
4546 }
4547
JF Bastien7f0a05a2018-05-25 00:07:09 +00004548 // All atomic operations have an overload which takes a pointer to a volatile
4549 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4550 // into the result or the other operands. Similarly atomic_load takes a
4551 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00004552 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00004553 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004554 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00004555 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4556 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004557 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00004558 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004559 ResultType = Context.BoolTy;
4560
Richard Smithfeea8832012-04-12 05:08:17 +00004561 // The type of a parameter passed 'by value'. In the GNU atomics, such
4562 // arguments are actually passed as pointers.
4563 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00004564 bool IsPassedByAddress = false;
4565 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00004566 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00004567 IsPassedByAddress = true;
4568 }
Richard Smithfeea8832012-04-12 05:08:17 +00004569
JF Bastien7f0a05a2018-05-25 00:07:09 +00004570 // The first argument's non-CV pointer type is used to deduce the type of
4571 // subsequent arguments, except for:
4572 // - weak flag (always converted to bool)
4573 // - memory order (always converted to int)
4574 // - scope (always converted to int)
4575 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004576 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00004577 if (i < NumVals[Form] + 1) {
4578 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00004579 case 0:
4580 // The first argument is always a pointer. It has a fixed type.
4581 // It is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004582 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
JF Bastien7f0a05a2018-05-25 00:07:09 +00004583 // Nothing else to do: we already know all we want about this pointer.
4584 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00004585 case 1:
4586 // The second argument is the non-atomic operand. For arithmetic, this
4587 // is always passed by value, and for a compare_exchange it is always
4588 // passed by address. For the rest, GNU uses by-address and C11 uses
4589 // by-value.
4590 assert(Form != Load);
4591 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4592 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004593 else if (Form == Copy || Form == Xchg) {
4594 if (IsPassedByAddress)
4595 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004596 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004597 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004598 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00004599 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004600 else {
4601 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00004602 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004603 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
Alexander Richardson6d989432017-10-15 18:48:14 +00004604 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004605 // Keep address space of non-atomic pointer type.
4606 if (const PointerType *PtrTy =
4607 ValArg->getType()->getAs<PointerType>()) {
4608 AS = PtrTy->getPointeeType().getAddressSpace();
4609 }
4610 Ty = Context.getPointerType(
4611 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4612 }
Richard Smithfeea8832012-04-12 05:08:17 +00004613 break;
4614 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00004615 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00004616 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4617 if (IsPassedByAddress)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004618 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004619 Ty = ByValType;
4620 break;
4621 case 3:
4622 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4623 Ty = Context.BoolTy;
4624 break;
4625 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004626 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00004627 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004628 Ty = Context.IntTy;
4629 }
Richard Smithfeea8832012-04-12 05:08:17 +00004630
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004631 InitializedEntity Entity =
4632 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00004633 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004634 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4635 if (Arg.isInvalid())
4636 return true;
4637 TheCall->setArg(i, Arg.get());
4638 }
4639
Richard Smithfeea8832012-04-12 05:08:17 +00004640 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004641 SmallVector<Expr*, 5> SubExprs;
4642 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00004643 switch (Form) {
4644 case Init:
4645 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00004646 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004647 break;
4648 case Load:
4649 SubExprs.push_back(TheCall->getArg(1)); // Order
4650 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00004651 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00004652 case Copy:
4653 case Arithmetic:
4654 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004655 SubExprs.push_back(TheCall->getArg(2)); // Order
4656 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004657 break;
4658 case GNUXchg:
4659 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4660 SubExprs.push_back(TheCall->getArg(3)); // Order
4661 SubExprs.push_back(TheCall->getArg(1)); // Val1
4662 SubExprs.push_back(TheCall->getArg(2)); // Val2
4663 break;
4664 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004665 SubExprs.push_back(TheCall->getArg(3)); // Order
4666 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004667 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00004668 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00004669 break;
4670 case GNUCmpXchg:
4671 SubExprs.push_back(TheCall->getArg(4)); // Order
4672 SubExprs.push_back(TheCall->getArg(1)); // Val1
4673 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4674 SubExprs.push_back(TheCall->getArg(2)); // Val2
4675 SubExprs.push_back(TheCall->getArg(3)); // Weak
4676 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004677 }
Tim Northovere94a34c2014-03-11 10:49:14 +00004678
4679 if (SubExprs.size() >= 2 && Form != Init) {
4680 llvm::APSInt Result(32);
4681 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4682 !isValidOrderingForOp(Result.getSExtValue(), Op))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004683 Diag(SubExprs[1]->getBeginLoc(),
Tim Northoverc83472e2014-03-11 11:35:10 +00004684 diag::warn_atomic_op_has_invalid_memory_order)
4685 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00004686 }
4687
Yaxun Liu30d652a2017-08-15 16:02:49 +00004688 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4689 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4690 llvm::APSInt Result(32);
4691 if (Scope->isIntegerConstantExpr(Result, Context) &&
4692 !ScopeModel->isValid(Result.getZExtValue())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004693 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
Yaxun Liu30d652a2017-08-15 16:02:49 +00004694 << Scope->getSourceRange();
4695 }
4696 SubExprs.push_back(Scope);
4697 }
4698
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004699 AtomicExpr *AE =
4700 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4701 ResultType, Op, TheCall->getRParenLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00004702
Fariborz Jahanian615de762013-05-28 17:37:39 +00004703 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00004704 Op == AtomicExpr::AO__c11_atomic_store ||
4705 Op == AtomicExpr::AO__opencl_atomic_load ||
4706 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00004707 Context.AtomicUsesUnsupportedLibcall(AE))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004708 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
Yaxun Liu39195062017-08-04 18:16:31 +00004709 << ((Op == AtomicExpr::AO__c11_atomic_load ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004710 Op == AtomicExpr::AO__opencl_atomic_load)
4711 ? 0
4712 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004713
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004714 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004715}
4716
John McCall29ad95b2011-08-27 01:09:30 +00004717/// checkBuiltinArgument - Given a call to a builtin function, perform
4718/// normal type-checking on the given argument, updating the call in
4719/// place. This is useful when a builtin function requires custom
4720/// type-checking for some of its arguments but not necessarily all of
4721/// them.
4722///
4723/// Returns true on error.
4724static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4725 FunctionDecl *Fn = E->getDirectCallee();
4726 assert(Fn && "builtin call without direct callee!");
4727
4728 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4729 InitializedEntity Entity =
4730 InitializedEntity::InitializeParameter(S.Context, Param);
4731
4732 ExprResult Arg = E->getArg(0);
4733 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4734 if (Arg.isInvalid())
4735 return true;
4736
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004737 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00004738 return false;
4739}
4740
JF Bastiene77b48b2018-09-10 20:42:56 +00004741/// We have a call to a function like __sync_fetch_and_add, which is an
4742/// overloaded function based on the pointer type of its first argument.
4743/// The main ActOnCallExpr routines have already promoted the types of
4744/// arguments because all of these calls are prototyped as void(...).
Chris Lattnerdc046542009-05-08 06:58:22 +00004745///
4746/// This function goes through and does final semantic checking for these
JF Bastiene77b48b2018-09-10 20:42:56 +00004747/// builtins, as well as generating any warnings.
John McCalldadc5752010-08-24 06:29:42 +00004748ExprResult
4749Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
JF Bastiene77b48b2018-09-10 20:42:56 +00004750 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4751 Expr *Callee = TheCall->getCallee();
4752 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
Chris Lattnerdc046542009-05-08 06:58:22 +00004753 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4754
4755 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004756 if (TheCall->getNumArgs() < 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004757 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
JF Bastiene77b48b2018-09-10 20:42:56 +00004758 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004759 return ExprError();
4760 }
Mike Stump11289f42009-09-09 15:08:12 +00004761
Chris Lattnerdc046542009-05-08 06:58:22 +00004762 // Inspect the first argument of the atomic builtin. This should always be
4763 // a pointer type, whose element is an integral scalar or pointer type.
4764 // Because it is a pointer type, we don't have to worry about any implicit
4765 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004766 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00004767 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00004768 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4769 if (FirstArgResult.isInvalid())
4770 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004771 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00004772 TheCall->setArg(0, FirstArg);
4773
John McCall31168b02011-06-15 23:02:42 +00004774 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4775 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004776 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4777 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004778 return ExprError();
4779 }
Mike Stump11289f42009-09-09 15:08:12 +00004780
John McCall31168b02011-06-15 23:02:42 +00004781 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00004782 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004783 !ValType->isBlockPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004784 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4785 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004786 return ExprError();
4787 }
Chris Lattnerdc046542009-05-08 06:58:22 +00004788
Aaron Ballmana383c942018-05-05 17:38:42 +00004789 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004790 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
Aaron Ballmana383c942018-05-05 17:38:42 +00004791 << FirstArg->getType() << FirstArg->getSourceRange();
4792 return ExprError();
4793 }
4794
John McCall31168b02011-06-15 23:02:42 +00004795 switch (ValType.getObjCLifetime()) {
4796 case Qualifiers::OCL_None:
4797 case Qualifiers::OCL_ExplicitNone:
4798 // okay
4799 break;
4800
4801 case Qualifiers::OCL_Weak:
4802 case Qualifiers::OCL_Strong:
4803 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004804 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4805 << ValType << FirstArg->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004806 return ExprError();
4807 }
4808
John McCallb50451a2011-10-05 07:41:44 +00004809 // Strip any qualifiers off ValType.
4810 ValType = ValType.getUnqualifiedType();
4811
Chandler Carruth3973af72010-07-18 20:54:12 +00004812 // The majority of builtins return a value, but a few have special return
4813 // types, so allow them to override appropriately below.
4814 QualType ResultType = ValType;
4815
Chris Lattnerdc046542009-05-08 06:58:22 +00004816 // We need to figure out which concrete builtin this maps onto. For example,
4817 // __sync_fetch_and_add with a 2 byte object turns into
4818 // __sync_fetch_and_add_2.
4819#define BUILTIN_ROW(x) \
4820 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4821 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00004822
Chris Lattnerdc046542009-05-08 06:58:22 +00004823 static const unsigned BuiltinIndices[][5] = {
4824 BUILTIN_ROW(__sync_fetch_and_add),
4825 BUILTIN_ROW(__sync_fetch_and_sub),
4826 BUILTIN_ROW(__sync_fetch_and_or),
4827 BUILTIN_ROW(__sync_fetch_and_and),
4828 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00004829 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00004830
Chris Lattnerdc046542009-05-08 06:58:22 +00004831 BUILTIN_ROW(__sync_add_and_fetch),
4832 BUILTIN_ROW(__sync_sub_and_fetch),
4833 BUILTIN_ROW(__sync_and_and_fetch),
4834 BUILTIN_ROW(__sync_or_and_fetch),
4835 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00004836 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00004837
Chris Lattnerdc046542009-05-08 06:58:22 +00004838 BUILTIN_ROW(__sync_val_compare_and_swap),
4839 BUILTIN_ROW(__sync_bool_compare_and_swap),
4840 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00004841 BUILTIN_ROW(__sync_lock_release),
4842 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00004843 };
Mike Stump11289f42009-09-09 15:08:12 +00004844#undef BUILTIN_ROW
4845
Chris Lattnerdc046542009-05-08 06:58:22 +00004846 // Determine the index of the size.
4847 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00004848 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00004849 case 1: SizeIndex = 0; break;
4850 case 2: SizeIndex = 1; break;
4851 case 4: SizeIndex = 2; break;
4852 case 8: SizeIndex = 3; break;
4853 case 16: SizeIndex = 4; break;
4854 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004855 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4856 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004857 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00004858 }
Mike Stump11289f42009-09-09 15:08:12 +00004859
Chris Lattnerdc046542009-05-08 06:58:22 +00004860 // Each of these builtins has one pointer argument, followed by some number of
4861 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4862 // that we ignore. Find out which row of BuiltinIndices to read from as well
4863 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00004864 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00004865 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00004866 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00004867 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00004868 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Fangrui Song6907ce22018-07-30 19:24:48 +00004869 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00004870 case Builtin::BI__sync_fetch_and_add_1:
4871 case Builtin::BI__sync_fetch_and_add_2:
4872 case Builtin::BI__sync_fetch_and_add_4:
4873 case Builtin::BI__sync_fetch_and_add_8:
4874 case Builtin::BI__sync_fetch_and_add_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004875 BuiltinIndex = 0;
Douglas Gregor73722482011-11-28 16:30:08 +00004876 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004877
4878 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00004879 case Builtin::BI__sync_fetch_and_sub_1:
4880 case Builtin::BI__sync_fetch_and_sub_2:
4881 case Builtin::BI__sync_fetch_and_sub_4:
4882 case Builtin::BI__sync_fetch_and_sub_8:
4883 case Builtin::BI__sync_fetch_and_sub_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004884 BuiltinIndex = 1;
Douglas Gregor73722482011-11-28 16:30:08 +00004885 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004886
4887 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00004888 case Builtin::BI__sync_fetch_and_or_1:
4889 case Builtin::BI__sync_fetch_and_or_2:
4890 case Builtin::BI__sync_fetch_and_or_4:
4891 case Builtin::BI__sync_fetch_and_or_8:
4892 case Builtin::BI__sync_fetch_and_or_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004893 BuiltinIndex = 2;
Douglas Gregor73722482011-11-28 16:30:08 +00004894 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004895
4896 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00004897 case Builtin::BI__sync_fetch_and_and_1:
4898 case Builtin::BI__sync_fetch_and_and_2:
4899 case Builtin::BI__sync_fetch_and_and_4:
4900 case Builtin::BI__sync_fetch_and_and_8:
4901 case Builtin::BI__sync_fetch_and_and_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004902 BuiltinIndex = 3;
Douglas Gregor73722482011-11-28 16:30:08 +00004903 break;
Mike Stump11289f42009-09-09 15:08:12 +00004904
Fangrui Song6907ce22018-07-30 19:24:48 +00004905 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00004906 case Builtin::BI__sync_fetch_and_xor_1:
4907 case Builtin::BI__sync_fetch_and_xor_2:
4908 case Builtin::BI__sync_fetch_and_xor_4:
4909 case Builtin::BI__sync_fetch_and_xor_8:
4910 case Builtin::BI__sync_fetch_and_xor_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004911 BuiltinIndex = 4;
Douglas Gregor73722482011-11-28 16:30:08 +00004912 break;
4913
Fangrui Song6907ce22018-07-30 19:24:48 +00004914 case Builtin::BI__sync_fetch_and_nand:
Hal Finkeld2208b52014-10-02 20:53:50 +00004915 case Builtin::BI__sync_fetch_and_nand_1:
4916 case Builtin::BI__sync_fetch_and_nand_2:
4917 case Builtin::BI__sync_fetch_and_nand_4:
4918 case Builtin::BI__sync_fetch_and_nand_8:
4919 case Builtin::BI__sync_fetch_and_nand_16:
4920 BuiltinIndex = 5;
4921 WarnAboutSemanticsChange = true;
4922 break;
4923
Fangrui Song6907ce22018-07-30 19:24:48 +00004924 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004925 case Builtin::BI__sync_add_and_fetch_1:
4926 case Builtin::BI__sync_add_and_fetch_2:
4927 case Builtin::BI__sync_add_and_fetch_4:
4928 case Builtin::BI__sync_add_and_fetch_8:
4929 case Builtin::BI__sync_add_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004930 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00004931 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004932
4933 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004934 case Builtin::BI__sync_sub_and_fetch_1:
4935 case Builtin::BI__sync_sub_and_fetch_2:
4936 case Builtin::BI__sync_sub_and_fetch_4:
4937 case Builtin::BI__sync_sub_and_fetch_8:
4938 case Builtin::BI__sync_sub_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004939 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00004940 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004941
4942 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004943 case Builtin::BI__sync_and_and_fetch_1:
4944 case Builtin::BI__sync_and_and_fetch_2:
4945 case Builtin::BI__sync_and_and_fetch_4:
4946 case Builtin::BI__sync_and_and_fetch_8:
4947 case Builtin::BI__sync_and_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004948 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00004949 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004950
4951 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004952 case Builtin::BI__sync_or_and_fetch_1:
4953 case Builtin::BI__sync_or_and_fetch_2:
4954 case Builtin::BI__sync_or_and_fetch_4:
4955 case Builtin::BI__sync_or_and_fetch_8:
4956 case Builtin::BI__sync_or_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004957 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00004958 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004959
4960 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004961 case Builtin::BI__sync_xor_and_fetch_1:
4962 case Builtin::BI__sync_xor_and_fetch_2:
4963 case Builtin::BI__sync_xor_and_fetch_4:
4964 case Builtin::BI__sync_xor_and_fetch_8:
4965 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004966 BuiltinIndex = 10;
4967 break;
4968
Fangrui Song6907ce22018-07-30 19:24:48 +00004969 case Builtin::BI__sync_nand_and_fetch:
Hal Finkeld2208b52014-10-02 20:53:50 +00004970 case Builtin::BI__sync_nand_and_fetch_1:
4971 case Builtin::BI__sync_nand_and_fetch_2:
4972 case Builtin::BI__sync_nand_and_fetch_4:
4973 case Builtin::BI__sync_nand_and_fetch_8:
4974 case Builtin::BI__sync_nand_and_fetch_16:
4975 BuiltinIndex = 11;
4976 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00004977 break;
Mike Stump11289f42009-09-09 15:08:12 +00004978
Chris Lattnerdc046542009-05-08 06:58:22 +00004979 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004980 case Builtin::BI__sync_val_compare_and_swap_1:
4981 case Builtin::BI__sync_val_compare_and_swap_2:
4982 case Builtin::BI__sync_val_compare_and_swap_4:
4983 case Builtin::BI__sync_val_compare_and_swap_8:
4984 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004985 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00004986 NumFixed = 2;
4987 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004988
Chris Lattnerdc046542009-05-08 06:58:22 +00004989 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004990 case Builtin::BI__sync_bool_compare_and_swap_1:
4991 case Builtin::BI__sync_bool_compare_and_swap_2:
4992 case Builtin::BI__sync_bool_compare_and_swap_4:
4993 case Builtin::BI__sync_bool_compare_and_swap_8:
4994 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004995 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00004996 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00004997 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004998 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004999
JF Bastien7f0a05a2018-05-25 00:07:09 +00005000 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00005001 case Builtin::BI__sync_lock_test_and_set_1:
5002 case Builtin::BI__sync_lock_test_and_set_2:
5003 case Builtin::BI__sync_lock_test_and_set_4:
5004 case Builtin::BI__sync_lock_test_and_set_8:
5005 case Builtin::BI__sync_lock_test_and_set_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005006 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00005007 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005008
Chris Lattnerdc046542009-05-08 06:58:22 +00005009 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00005010 case Builtin::BI__sync_lock_release_1:
5011 case Builtin::BI__sync_lock_release_2:
5012 case Builtin::BI__sync_lock_release_4:
5013 case Builtin::BI__sync_lock_release_8:
5014 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005015 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00005016 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00005017 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005018 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005019
5020 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005021 case Builtin::BI__sync_swap_1:
5022 case Builtin::BI__sync_swap_2:
5023 case Builtin::BI__sync_swap_4:
5024 case Builtin::BI__sync_swap_8:
5025 case Builtin::BI__sync_swap_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005026 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00005027 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00005028 }
Mike Stump11289f42009-09-09 15:08:12 +00005029
Chris Lattnerdc046542009-05-08 06:58:22 +00005030 // Now that we know how many fixed arguments we expect, first check that we
5031 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005032 if (TheCall->getNumArgs() < 1+NumFixed) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005033 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5034 << 0 << 1 + NumFixed << TheCall->getNumArgs()
JF Bastiene77b48b2018-09-10 20:42:56 +00005035 << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005036 return ExprError();
5037 }
Mike Stump11289f42009-09-09 15:08:12 +00005038
JF Bastiene77b48b2018-09-10 20:42:56 +00005039 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5040 << Callee->getSourceRange();
5041
Hal Finkeld2208b52014-10-02 20:53:50 +00005042 if (WarnAboutSemanticsChange) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005043 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
JF Bastiene77b48b2018-09-10 20:42:56 +00005044 << Callee->getSourceRange();
Hal Finkeld2208b52014-10-02 20:53:50 +00005045 }
5046
Chris Lattner5b9241b2009-05-08 15:36:58 +00005047 // Get the decl for the concrete builtin from this, we can tell what the
5048 // concrete integer type we should convert to is.
5049 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00005050 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005051 FunctionDecl *NewBuiltinDecl;
5052 if (NewBuiltinID == BuiltinID)
5053 NewBuiltinDecl = FDecl;
5054 else {
5055 // Perform builtin lookup to avoid redeclaring it.
5056 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005057 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005058 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5059 assert(Res.getFoundDecl());
5060 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005061 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005062 return ExprError();
5063 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005064
John McCallcf142162010-08-07 06:22:56 +00005065 // The first argument --- the pointer --- has a fixed type; we
5066 // deduce the types of the rest of the arguments accordingly. Walk
5067 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00005068 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00005069 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00005070
Chris Lattnerdc046542009-05-08 06:58:22 +00005071 // GCC does an implicit conversion to the pointer or integer ValType. This
5072 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00005073 // Initialize the argument.
5074 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5075 ValType, /*consume*/ false);
5076 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00005077 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005078 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005079
Chris Lattnerdc046542009-05-08 06:58:22 +00005080 // Okay, we have something that *can* be converted to the right type. Check
5081 // to see if there is a potentially weird extension going on here. This can
5082 // happen when you do an atomic operation on something like an char* and
5083 // pass in 42. The 42 gets converted to char. This is even more strange
5084 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00005085 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005086 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00005087 }
Mike Stump11289f42009-09-09 15:08:12 +00005088
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005089 ASTContext& Context = this->getASTContext();
5090
5091 // Create a new DeclRefExpr to refer to the new decl.
5092 DeclRefExpr* NewDRE = DeclRefExpr::Create(
5093 Context,
5094 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00005095 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005096 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00005097 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005098 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00005099 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005100 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00005101
Chris Lattnerdc046542009-05-08 06:58:22 +00005102 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00005103 // FIXME: This loses syntactic information.
5104 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5105 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5106 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005107 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00005108
Chandler Carruthbc8cab12010-07-18 07:23:17 +00005109 // Change the result type of the call to match the original value type. This
5110 // is arbitrary, but the codegen for these builtins ins design to handle it
5111 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00005112 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005113
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005114 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00005115}
5116
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005117/// SemaBuiltinNontemporalOverloaded - We have a call to
5118/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5119/// overloaded function based on the pointer type of its last argument.
5120///
5121/// This function goes through and does final semantic checking for these
5122/// builtins.
5123ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5124 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5125 DeclRefExpr *DRE =
5126 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5127 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5128 unsigned BuiltinID = FDecl->getBuiltinID();
5129 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5130 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5131 "Unexpected nontemporal load/store builtin!");
5132 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5133 unsigned numArgs = isStore ? 2 : 1;
5134
5135 // Ensure that we have the proper number of arguments.
5136 if (checkArgCount(*this, TheCall, numArgs))
5137 return ExprError();
5138
5139 // Inspect the last argument of the nontemporal builtin. This should always
5140 // be a pointer type, from which we imply the type of the memory access.
5141 // Because it is a pointer type, we don't have to worry about any implicit
5142 // casts here.
5143 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5144 ExprResult PointerArgResult =
5145 DefaultFunctionArrayLvalueConversion(PointerArg);
5146
5147 if (PointerArgResult.isInvalid())
5148 return ExprError();
5149 PointerArg = PointerArgResult.get();
5150 TheCall->setArg(numArgs - 1, PointerArg);
5151
5152 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5153 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005154 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005155 << PointerArg->getType() << PointerArg->getSourceRange();
5156 return ExprError();
5157 }
5158
5159 QualType ValType = pointerType->getPointeeType();
5160
5161 // Strip any qualifiers off ValType.
5162 ValType = ValType.getUnqualifiedType();
5163 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5164 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5165 !ValType->isVectorType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005166 Diag(DRE->getBeginLoc(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005167 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5168 << PointerArg->getType() << PointerArg->getSourceRange();
5169 return ExprError();
5170 }
5171
5172 if (!isStore) {
5173 TheCall->setType(ValType);
5174 return TheCallResult;
5175 }
5176
5177 ExprResult ValArg = TheCall->getArg(0);
5178 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5179 Context, ValType, /*consume*/ false);
5180 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5181 if (ValArg.isInvalid())
5182 return ExprError();
5183
5184 TheCall->setArg(0, ValArg.get());
5185 TheCall->setType(Context.VoidTy);
5186 return TheCallResult;
5187}
5188
Chris Lattner6436fb62009-02-18 06:01:06 +00005189/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00005190/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00005191/// Note: It might also make sense to do the UTF-16 conversion here (would
5192/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00005193bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00005194 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00005195 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5196
Douglas Gregorfb65e592011-07-27 05:40:30 +00005197 if (!Literal || !Literal->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005198 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5199 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00005200 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00005201 }
Mike Stump11289f42009-09-09 15:08:12 +00005202
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005203 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005204 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005205 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00005206 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5207 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5208 llvm::UTF16 *ToPtr = &ToBuf[0];
5209
5210 llvm::ConversionResult Result =
5211 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5212 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005213 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00005214 if (Result != llvm::conversionOK)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005215 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5216 << Arg->getSourceRange();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005217 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00005218 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005219}
5220
Mehdi Amini06d367c2016-10-24 20:39:34 +00005221/// CheckObjCString - Checks that the format string argument to the os_log()
5222/// and os_trace() functions is correct, and converts it to const char *.
5223ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5224 Arg = Arg->IgnoreParenCasts();
5225 auto *Literal = dyn_cast<StringLiteral>(Arg);
5226 if (!Literal) {
5227 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5228 Literal = ObjcLiteral->getString();
5229 }
5230 }
5231
5232 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5233 return ExprError(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005234 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005235 << Arg->getSourceRange());
5236 }
5237
5238 ExprResult Result(Literal);
5239 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5240 InitializedEntity Entity =
5241 InitializedEntity::InitializeParameter(Context, ResultTy, false);
5242 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5243 return Result;
5244}
5245
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005246/// Check that the user is calling the appropriate va_start builtin for the
5247/// target and calling convention.
5248static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5249 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5250 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00005251 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005252 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00005253 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5254 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005255 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005256 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5257 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5258 if (IsMSVAStart) {
5259 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00005260 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005261 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005262 diag::err_ms_va_start_used_in_sysv_function);
5263 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00005264 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005265 // On x64 Windows, don't allow this in System V ABI functions.
5266 // (Yes, that means there's no corresponding way to support variadic
5267 // System V ABI functions on Windows.)
5268 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00005269 (!IsWindows && CC == CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005270 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005271 diag::err_va_start_used_in_wrong_abi_function)
5272 << !IsWindows;
5273 }
5274 return false;
5275 }
5276
5277 if (IsMSVAStart)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005278 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005279 return false;
5280}
5281
5282static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5283 ParmVarDecl **LastParam = nullptr) {
5284 // Determine whether the current function, block, or obj-c method is variadic
5285 // and get its parameter list.
5286 bool IsVariadic = false;
5287 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00005288 DeclContext *Caller = S.CurContext;
5289 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5290 IsVariadic = Block->isVariadic();
5291 Params = Block->parameters();
5292 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005293 IsVariadic = FD->isVariadic();
5294 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005295 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005296 IsVariadic = MD->isVariadic();
5297 // FIXME: This isn't correct for methods (results in bogus warning).
5298 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005299 } else if (isa<CapturedDecl>(Caller)) {
5300 // We don't support va_start in a CapturedDecl.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005301 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005302 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005303 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00005304 // This must be some other declcontext that parses exprs.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005305 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005306 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005307 }
5308
5309 if (!IsVariadic) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005310 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005311 return true;
5312 }
5313
5314 if (LastParam)
5315 *LastParam = Params.empty() ? nullptr : Params.back();
5316
5317 return false;
5318}
5319
Aaron Ballman68d50642018-06-19 14:53:20 +00005320/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5321/// for validity. Emit an error and return true on failure; return false
5322/// on success.
5323bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5324 Expr *Fn = TheCall->getCallee();
5325
5326 if (checkVAStartABI(*this, BuiltinID, Fn))
5327 return true;
5328
5329 if (TheCall->getNumArgs() > 2) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005330 Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005331 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005332 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5333 << Fn->getSourceRange()
5334 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005335 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005336 return true;
5337 }
5338
5339 if (TheCall->getNumArgs() < 2) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005340 return Diag(TheCall->getEndLoc(),
5341 diag::err_typecheck_call_too_few_args_at_least)
5342 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Aaron Ballman68d50642018-06-19 14:53:20 +00005343 }
5344
5345 // Type-check the first argument normally.
5346 if (checkBuiltinArgument(*this, TheCall, 0))
5347 return true;
5348
5349 // Check that the current function is variadic, and get its last parameter.
5350 ParmVarDecl *LastParam;
5351 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5352 return true;
5353
5354 // Verify that the second argument to the builtin is the last argument of the
5355 // current function or method.
5356 bool SecondArgIsLastNamedArgument = false;
5357 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5358
5359 // These are valid if SecondArgIsLastNamedArgument is false after the next
5360 // block.
5361 QualType Type;
5362 SourceLocation ParamLoc;
5363 bool IsCRegister = false;
5364
5365 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5366 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5367 SecondArgIsLastNamedArgument = PV == LastParam;
5368
5369 Type = PV->getType();
5370 ParamLoc = PV->getLocation();
5371 IsCRegister =
5372 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5373 }
5374 }
5375
5376 if (!SecondArgIsLastNamedArgument)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005377 Diag(TheCall->getArg(1)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005378 diag::warn_second_arg_of_va_start_not_last_named_param);
5379 else if (IsCRegister || Type->isReferenceType() ||
5380 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5381 // Promotable integers are UB, but enumerations need a bit of
5382 // extra checking to see what their promotable type actually is.
5383 if (!Type->isPromotableIntegerType())
5384 return false;
5385 if (!Type->isEnumeralType())
5386 return true;
5387 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5388 return !(ED &&
5389 Context.typesAreCompatible(ED->getPromotionType(), Type));
5390 }()) {
5391 unsigned Reason = 0;
5392 if (Type->isReferenceType()) Reason = 1;
5393 else if (IsCRegister) Reason = 2;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005394 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
Aaron Ballman68d50642018-06-19 14:53:20 +00005395 Diag(ParamLoc, diag::note_parameter_type) << Type;
5396 }
5397
5398 TheCall->setType(Context.VoidTy);
5399 return false;
5400}
5401
5402bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5403 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5404 // const char *named_addr);
5405
5406 Expr *Func = Call->getCallee();
5407
5408 if (Call->getNumArgs() < 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005409 return Diag(Call->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005410 diag::err_typecheck_call_too_few_args_at_least)
5411 << 0 /*function call*/ << 3 << Call->getNumArgs();
5412
5413 // Type-check the first argument normally.
5414 if (checkBuiltinArgument(*this, Call, 0))
5415 return true;
5416
5417 // Check that the current function is variadic.
5418 if (checkVAStartIsInVariadicFunction(*this, Func))
5419 return true;
5420
5421 // __va_start on Windows does not validate the parameter qualifiers
5422
5423 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5424 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5425
5426 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5427 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5428
5429 const QualType &ConstCharPtrTy =
5430 Context.getPointerType(Context.CharTy.withConst());
5431 if (!Arg1Ty->isPointerType() ||
5432 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005433 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5434 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5435 << 0 /* qualifier difference */
5436 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005437 << 2 << Arg1->getType() << ConstCharPtrTy;
5438
5439 const QualType SizeTy = Context.getSizeType();
5440 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005441 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5442 << Arg2->getType() << SizeTy << 1 /* different class */
5443 << 0 /* qualifier difference */
5444 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005445 << 3 << Arg2->getType() << SizeTy;
5446
5447 return false;
5448}
5449
5450/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5451/// friends. This is declared to take (...), so we have to check everything.
5452bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5453 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005454 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5455 << 0 << 2 << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005456 if (TheCall->getNumArgs() > 2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005457 return Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005458 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005459 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5460 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005461 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005462
5463 ExprResult OrigArg0 = TheCall->getArg(0);
5464 ExprResult OrigArg1 = TheCall->getArg(1);
5465
5466 // Do standard promotions between the two arguments, returning their common
5467 // type.
5468 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5469 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5470 return true;
5471
5472 // Make sure any conversions are pushed back into the call; this is
5473 // type safe since unordered compare builtins are declared as "_Bool
5474 // foo(...)".
5475 TheCall->setArg(0, OrigArg0.get());
5476 TheCall->setArg(1, OrigArg1.get());
5477
5478 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5479 return false;
5480
5481 // If the common type isn't a real floating type, then the arguments were
5482 // invalid for this operation.
5483 if (Res.isNull() || !Res->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005484 return Diag(OrigArg0.get()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005485 diag::err_typecheck_call_invalid_ordered_compare)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005486 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5487 << SourceRange(OrigArg0.get()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005488 OrigArg1.get()->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005489
5490 return false;
5491}
5492
5493/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5494/// __builtin_isnan and friends. This is declared to take (...), so we have
5495/// to check everything. We expect the last argument to be a floating point
5496/// value.
5497bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5498 if (TheCall->getNumArgs() < NumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005499 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5500 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005501 if (TheCall->getNumArgs() > NumArgs)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005502 return Diag(TheCall->getArg(NumArgs)->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*/ << NumArgs << TheCall->getNumArgs()
5505 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005506 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005507
5508 Expr *OrigArg = TheCall->getArg(NumArgs-1);
5509
5510 if (OrigArg->isTypeDependent())
5511 return false;
5512
5513 // This operation requires a non-_Complex floating-point number.
5514 if (!OrigArg->getType()->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005515 return Diag(OrigArg->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005516 diag::err_typecheck_call_invalid_unary_fp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005517 << OrigArg->getType() << OrigArg->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005518
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005519 // If this is an implicit conversion from float -> float, double, or
5520 // long double, remove it.
Aaron Ballman68d50642018-06-19 14:53:20 +00005521 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5522 // Only remove standard FloatCasts, leaving other casts inplace
5523 if (Cast->getCastKind() == CK_FloatingCast) {
5524 Expr *CastArg = Cast->getSubExpr();
5525 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005526 assert(
5527 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5528 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5529 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5530 "promotion from float to either float, double, or long double is "
5531 "the only expected cast here");
Aaron Ballman68d50642018-06-19 14:53:20 +00005532 Cast->setSubExpr(nullptr);
5533 TheCall->setArg(NumArgs-1, CastArg);
5534 }
5535 }
5536 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005537
Aaron Ballman68d50642018-06-19 14:53:20 +00005538 return false;
5539}
5540
5541// Customized Sema Checking for VSX builtins that have the following signature:
5542// vector [...] builtinName(vector [...], vector [...], const int);
5543// Which takes the same type of vectors (any legal vector type) for the first
5544// two arguments and takes compile time constant for the third argument.
5545// Example builtins are :
5546// vector double vec_xxpermdi(vector double, vector double, int);
5547// vector short vec_xxsldwi(vector short, vector short, int);
5548bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5549 unsigned ExpectedNumArgs = 3;
5550 if (TheCall->getNumArgs() < ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005551 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005552 diag::err_typecheck_call_too_few_args_at_least)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005553 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
Aaron Ballman68d50642018-06-19 14:53:20 +00005554 << TheCall->getSourceRange();
5555
5556 if (TheCall->getNumArgs() > ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005557 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005558 diag::err_typecheck_call_too_many_args_at_most)
5559 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5560 << TheCall->getSourceRange();
5561
5562 // Check the third argument is a compile time constant
5563 llvm::APSInt Value;
5564 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005565 return Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005566 diag::err_vsx_builtin_nonconstant_argument)
5567 << 3 /* argument index */ << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005568 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005569 TheCall->getArg(2)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005570
5571 QualType Arg1Ty = TheCall->getArg(0)->getType();
5572 QualType Arg2Ty = TheCall->getArg(1)->getType();
5573
5574 // Check the type of argument 1 and argument 2 are vectors.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005575 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
Aaron Ballman68d50642018-06-19 14:53:20 +00005576 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5577 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5578 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5579 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005580 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005581 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005582 }
5583
5584 // Check the first two arguments are the same type.
5585 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5586 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5587 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005588 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005589 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005590 }
5591
5592 // When default clang type checking is turned off and the customized type
5593 // checking is used, the returning type of the function must be explicitly
5594 // set. Otherwise it is _Bool by default.
5595 TheCall->setType(Arg1Ty);
5596
5597 return false;
5598}
5599
5600/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5601// This is declared to take (...), so we have to check everything.
5602ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5603 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005604 return ExprError(Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005605 diag::err_typecheck_call_too_few_args_at_least)
5606 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5607 << TheCall->getSourceRange());
5608
5609 // Determine which of the following types of shufflevector we're checking:
5610 // 1) unary, vector mask: (lhs, mask)
5611 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5612 QualType resType = TheCall->getArg(0)->getType();
5613 unsigned numElements = 0;
5614
5615 if (!TheCall->getArg(0)->isTypeDependent() &&
5616 !TheCall->getArg(1)->isTypeDependent()) {
5617 QualType LHSType = TheCall->getArg(0)->getType();
5618 QualType RHSType = TheCall->getArg(1)->getType();
5619
5620 if (!LHSType->isVectorType() || !RHSType->isVectorType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005621 return ExprError(
5622 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5623 << TheCall->getDirectCallee()
5624 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005625 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005626
5627 numElements = LHSType->getAs<VectorType>()->getNumElements();
5628 unsigned numResElements = TheCall->getNumArgs() - 2;
5629
5630 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5631 // with mask. If so, verify that RHS is an integer vector type with the
5632 // same number of elts as lhs.
5633 if (TheCall->getNumArgs() == 2) {
5634 if (!RHSType->hasIntegerRepresentation() ||
5635 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005636 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005637 diag::err_vec_builtin_incompatible_vector)
5638 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005639 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005640 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005641 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005642 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005643 diag::err_vec_builtin_incompatible_vector)
5644 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005645 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005646 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005647 } else if (numElements != numResElements) {
5648 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5649 resType = Context.getVectorType(eltType, numResElements,
5650 VectorType::GenericVector);
5651 }
5652 }
5653
5654 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5655 if (TheCall->getArg(i)->isTypeDependent() ||
5656 TheCall->getArg(i)->isValueDependent())
5657 continue;
5658
5659 llvm::APSInt Result(32);
5660 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005661 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005662 diag::err_shufflevector_nonconstant_argument)
5663 << TheCall->getArg(i)->getSourceRange());
5664
5665 // Allow -1 which will be translated to undef in the IR.
5666 if (Result.isSigned() && Result.isAllOnesValue())
5667 continue;
5668
5669 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005670 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005671 diag::err_shufflevector_argument_too_large)
5672 << TheCall->getArg(i)->getSourceRange());
5673 }
5674
5675 SmallVector<Expr*, 32> exprs;
5676
5677 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5678 exprs.push_back(TheCall->getArg(i));
5679 TheCall->setArg(i, nullptr);
5680 }
5681
5682 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005683 TheCall->getCallee()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005684 TheCall->getRParenLoc());
5685}
5686
5687/// SemaConvertVectorExpr - Handle __builtin_convertvector
5688ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5689 SourceLocation BuiltinLoc,
5690 SourceLocation RParenLoc) {
5691 ExprValueKind VK = VK_RValue;
5692 ExprObjectKind OK = OK_Ordinary;
5693 QualType DstTy = TInfo->getType();
5694 QualType SrcTy = E->getType();
5695
5696 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5697 return ExprError(Diag(BuiltinLoc,
5698 diag::err_convertvector_non_vector)
5699 << E->getSourceRange());
5700 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5701 return ExprError(Diag(BuiltinLoc,
5702 diag::err_convertvector_non_vector_type));
5703
5704 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5705 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5706 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5707 if (SrcElts != DstElts)
5708 return ExprError(Diag(BuiltinLoc,
5709 diag::err_convertvector_incompatible_vector)
5710 << E->getSourceRange());
5711 }
5712
5713 return new (Context)
5714 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5715}
5716
5717/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5718// This is declared to take (const void*, ...) and can take two
5719// optional constant int args.
5720bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5721 unsigned NumArgs = TheCall->getNumArgs();
5722
5723 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005724 return Diag(TheCall->getEndLoc(),
5725 diag::err_typecheck_call_too_many_args_at_most)
5726 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005727
5728 // Argument 0 is checked for us and the remaining arguments must be
5729 // constant integers.
5730 for (unsigned i = 1; i != NumArgs; ++i)
Richard Sandiford28940af2014-04-16 08:47:51 +00005731 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005732 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005733
Warren Hunt20e4a5d2014-02-21 23:08:53 +00005734 return false;
5735}
5736
Hal Finkelf0417332014-07-17 14:25:55 +00005737/// SemaBuiltinAssume - Handle __assume (MS Extension).
5738// __assume does not evaluate its arguments, and should warn if its argument
5739// has side effects.
5740bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5741 Expr *Arg = TheCall->getArg(0);
5742 if (Arg->isInstantiationDependent()) return false;
5743
5744 if (Arg->HasSideEffects(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005745 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5746 << Arg->getSourceRange()
5747 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
Hal Finkelbcc06082014-09-07 22:58:14 +00005748
5749 return false;
5750}
5751
David Majnemer86b1bfa2016-10-31 18:07:57 +00005752/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00005753/// as (size_t, size_t) where the second size_t must be a power of 2 greater
5754/// than 8.
5755bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5756 // The alignment must be a constant integer.
5757 Expr *Arg = TheCall->getArg(1);
5758
5759 // We can't check the value of a dependent argument.
5760 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00005761 if (const auto *UE =
5762 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
Richard Smith6822bd72018-10-26 19:26:45 +00005763 if (UE->getKind() == UETT_AlignOf ||
5764 UE->getKind() == UETT_PreferredAlignOf)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005765 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5766 << Arg->getSourceRange();
David Majnemer86b1bfa2016-10-31 18:07:57 +00005767
David Majnemer51169932016-10-31 05:37:48 +00005768 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5769
5770 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005771 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5772 << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005773
5774 if (Result < Context.getCharWidth())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005775 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5776 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005777
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005778 if (Result > std::numeric_limits<int32_t>::max())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005779 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5780 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005781 }
5782
5783 return false;
5784}
5785
5786/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00005787/// as (const void*, size_t, ...) and can take one optional constant int arg.
5788bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5789 unsigned NumArgs = TheCall->getNumArgs();
5790
5791 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005792 return Diag(TheCall->getEndLoc(),
5793 diag::err_typecheck_call_too_many_args_at_most)
5794 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005795
5796 // The alignment must be a constant integer.
5797 Expr *Arg = TheCall->getArg(1);
5798
5799 // We can't check the value of a dependent argument.
5800 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5801 llvm::APSInt Result;
5802 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5803 return true;
5804
5805 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005806 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5807 << Arg->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005808 }
5809
5810 if (NumArgs > 2) {
5811 ExprResult Arg(TheCall->getArg(2));
5812 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5813 Context.getSizeType(), false);
5814 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5815 if (Arg.isInvalid()) return true;
5816 TheCall->setArg(2, Arg.get());
5817 }
Hal Finkelf0417332014-07-17 14:25:55 +00005818
5819 return false;
5820}
5821
Mehdi Amini06d367c2016-10-24 20:39:34 +00005822bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5823 unsigned BuiltinID =
5824 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5825 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5826
5827 unsigned NumArgs = TheCall->getNumArgs();
5828 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5829 if (NumArgs < NumRequiredArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005830 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005831 << 0 /* function call */ << NumRequiredArgs << NumArgs
5832 << TheCall->getSourceRange();
5833 }
5834 if (NumArgs >= NumRequiredArgs + 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005835 return Diag(TheCall->getEndLoc(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005836 diag::err_typecheck_call_too_many_args_at_most)
5837 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5838 << TheCall->getSourceRange();
5839 }
5840 unsigned i = 0;
5841
5842 // For formatting call, check buffer arg.
5843 if (!IsSizeCall) {
5844 ExprResult Arg(TheCall->getArg(i));
5845 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5846 Context, Context.VoidPtrTy, false);
5847 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5848 if (Arg.isInvalid())
5849 return true;
5850 TheCall->setArg(i, Arg.get());
5851 i++;
5852 }
5853
5854 // Check string literal arg.
5855 unsigned FormatIdx = i;
5856 {
5857 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5858 if (Arg.isInvalid())
5859 return true;
5860 TheCall->setArg(i, Arg.get());
5861 i++;
5862 }
5863
5864 // Make sure variadic args are scalar.
5865 unsigned FirstDataArg = i;
5866 while (i < NumArgs) {
5867 ExprResult Arg = DefaultVariadicArgumentPromotion(
5868 TheCall->getArg(i), VariadicFunction, nullptr);
5869 if (Arg.isInvalid())
5870 return true;
5871 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5872 if (ArgSize.getQuantity() >= 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005873 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005874 << i << (int)ArgSize.getQuantity() << 0xff
5875 << TheCall->getSourceRange();
5876 }
5877 TheCall->setArg(i, Arg.get());
5878 i++;
5879 }
5880
5881 // Check formatting specifiers. NOTE: We're only doing this for the non-size
5882 // call to avoid duplicate diagnostics.
5883 if (!IsSizeCall) {
5884 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5885 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5886 bool Success = CheckFormatArguments(
5887 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005888 VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005889 CheckedVarArgs);
5890 if (!Success)
5891 return true;
5892 }
5893
5894 if (IsSizeCall) {
5895 TheCall->setType(Context.getSizeType());
5896 } else {
5897 TheCall->setType(Context.VoidPtrTy);
5898 }
5899 return false;
5900}
5901
Eric Christopher8d0c6212010-04-17 02:26:23 +00005902/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5903/// TheCall is a constant expression.
5904bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5905 llvm::APSInt &Result) {
5906 Expr *Arg = TheCall->getArg(ArgNum);
5907 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5908 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00005909
Eric Christopher8d0c6212010-04-17 02:26:23 +00005910 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00005911
Eric Christopher8d0c6212010-04-17 02:26:23 +00005912 if (!Arg->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005913 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5914 << FDecl->getDeclName() << Arg->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00005915
Chris Lattnerd545ad12009-09-23 06:06:36 +00005916 return false;
5917}
5918
Richard Sandiford28940af2014-04-16 08:47:51 +00005919/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5920/// TheCall is a constant expression in the range [Low, High].
5921bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005922 int Low, int High, bool RangeIsError) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00005923 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005924
5925 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00005926 Expr *Arg = TheCall->getArg(ArgNum);
5927 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005928 return false;
5929
Eric Christopher8d0c6212010-04-17 02:26:23 +00005930 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00005931 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005932 return true;
5933
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005934 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5935 if (RangeIsError)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005936 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005937 << Result.toString(10) << Low << High << Arg->getSourceRange();
5938 else
5939 // Defer the warning until we know if the code will be emitted so that
5940 // dead code can ignore this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005941 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5942 PDiag(diag::warn_argument_invalid_range)
5943 << Result.toString(10) << Low << High
5944 << Arg->getSourceRange());
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005945 }
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00005946
5947 return false;
5948}
5949
Simon Dardis1f90f2d2016-10-19 17:50:52 +00005950/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5951/// TheCall is a constant expression is a multiple of Num..
5952bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5953 unsigned Num) {
5954 llvm::APSInt Result;
5955
5956 // We can't check the value of a dependent argument.
5957 Expr *Arg = TheCall->getArg(ArgNum);
5958 if (Arg->isTypeDependent() || Arg->isValueDependent())
5959 return false;
5960
5961 // Check constant-ness first.
5962 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5963 return true;
5964
5965 if (Result.getSExtValue() % Num != 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005966 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5967 << Num << Arg->getSourceRange();
Simon Dardis1f90f2d2016-10-19 17:50:52 +00005968
5969 return false;
5970}
5971
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005972/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5973/// TheCall is an ARM/AArch64 special register string literal.
5974bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5975 int ArgNum, unsigned ExpectedFieldNum,
5976 bool AllowName) {
5977 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5978 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5979 BuiltinID == ARM::BI__builtin_arm_rsr ||
5980 BuiltinID == ARM::BI__builtin_arm_rsrp ||
5981 BuiltinID == ARM::BI__builtin_arm_wsr ||
5982 BuiltinID == ARM::BI__builtin_arm_wsrp;
5983 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5984 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5985 BuiltinID == AArch64::BI__builtin_arm_rsr ||
5986 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5987 BuiltinID == AArch64::BI__builtin_arm_wsr ||
5988 BuiltinID == AArch64::BI__builtin_arm_wsrp;
5989 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5990
5991 // We can't check the value of a dependent argument.
5992 Expr *Arg = TheCall->getArg(ArgNum);
5993 if (Arg->isTypeDependent() || Arg->isValueDependent())
5994 return false;
5995
5996 // Check if the argument is a string literal.
5997 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005998 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005999 << Arg->getSourceRange();
6000
6001 // Check the type of special register given.
6002 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6003 SmallVector<StringRef, 6> Fields;
6004 Reg.split(Fields, ":");
6005
6006 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006007 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006008 << Arg->getSourceRange();
6009
6010 // If the string is the name of a register then we cannot check that it is
6011 // valid here but if the string is of one the forms described in ACLE then we
6012 // can check that the supplied fields are integers and within the valid
6013 // ranges.
6014 if (Fields.size() > 1) {
6015 bool FiveFields = Fields.size() == 5;
6016
6017 bool ValidString = true;
6018 if (IsARMBuiltin) {
6019 ValidString &= Fields[0].startswith_lower("cp") ||
6020 Fields[0].startswith_lower("p");
6021 if (ValidString)
6022 Fields[0] =
6023 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6024
6025 ValidString &= Fields[2].startswith_lower("c");
6026 if (ValidString)
6027 Fields[2] = Fields[2].drop_front(1);
6028
6029 if (FiveFields) {
6030 ValidString &= Fields[3].startswith_lower("c");
6031 if (ValidString)
6032 Fields[3] = Fields[3].drop_front(1);
6033 }
6034 }
6035
6036 SmallVector<int, 5> Ranges;
6037 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00006038 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006039 else
6040 Ranges.append({15, 7, 15});
6041
6042 for (unsigned i=0; i<Fields.size(); ++i) {
6043 int IntField;
6044 ValidString &= !Fields[i].getAsInteger(10, IntField);
6045 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6046 }
6047
6048 if (!ValidString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006049 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006050 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006051 } else if (IsAArch64Builtin && Fields.size() == 1) {
6052 // If the register name is one of those that appear in the condition below
6053 // and the special register builtin being used is one of the write builtins,
6054 // then we require that the argument provided for writing to the register
6055 // is an integer constant expression. This is because it will be lowered to
6056 // an MSR (immediate) instruction, so we need to know the immediate at
6057 // compile time.
6058 if (TheCall->getNumArgs() != 2)
6059 return false;
6060
6061 std::string RegLower = Reg.lower();
6062 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6063 RegLower != "pan" && RegLower != "uao")
6064 return false;
6065
6066 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6067 }
6068
6069 return false;
6070}
6071
Eli Friedmanc97d0142009-05-03 06:04:26 +00006072/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006073/// This checks that the target supports __builtin_longjmp and
6074/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006075bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006076 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006077 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006078 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006079
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006080 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00006081 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00006082
Eric Christopher8d0c6212010-04-17 02:26:23 +00006083 // TODO: This is less than ideal. Overload this to take a value.
6084 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6085 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006086
Eric Christopher8d0c6212010-04-17 02:26:23 +00006087 if (Result != 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006088 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006089 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006090
6091 return false;
6092}
6093
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006094/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6095/// This checks that the target supports __builtin_setjmp.
6096bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6097 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006098 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006099 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006100 return false;
6101}
6102
Richard Smithd7293d72013-08-05 18:49:43 +00006103namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006104
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006105class UncoveredArgHandler {
6106 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006107
6108 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006109 SmallVector<const Expr *, 4> DiagnosticExprs;
6110
6111public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006112 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006113
6114 bool hasUncoveredArg() const {
6115 return (FirstUncoveredArg >= 0);
6116 }
6117
6118 unsigned getUncoveredArg() const {
6119 assert(hasUncoveredArg() && "no uncovered argument");
6120 return FirstUncoveredArg;
6121 }
6122
6123 void setAllCovered() {
6124 // A string has been found with all arguments covered, so clear out
6125 // the diagnostics.
6126 DiagnosticExprs.clear();
6127 FirstUncoveredArg = AllCovered;
6128 }
6129
6130 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6131 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6132
6133 // Don't update if a previous string covers all arguments.
6134 if (FirstUncoveredArg == AllCovered)
6135 return;
6136
6137 // UncoveredArgHandler tracks the highest uncovered argument index
6138 // and with it all the strings that match this index.
6139 if (NewFirstUncoveredArg == FirstUncoveredArg)
6140 DiagnosticExprs.push_back(StrExpr);
6141 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6142 DiagnosticExprs.clear();
6143 DiagnosticExprs.push_back(StrExpr);
6144 FirstUncoveredArg = NewFirstUncoveredArg;
6145 }
6146 }
6147
6148 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6149};
6150
Richard Smithd7293d72013-08-05 18:49:43 +00006151enum StringLiteralCheckType {
6152 SLCT_NotALiteral,
6153 SLCT_UncheckedLiteral,
6154 SLCT_CheckedLiteral
6155};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006156
6157} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00006158
Stephen Hines648c3692016-09-16 01:07:04 +00006159static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6160 BinaryOperatorKind BinOpKind,
6161 bool AddendIsRight) {
6162 unsigned BitWidth = Offset.getBitWidth();
6163 unsigned AddendBitWidth = Addend.getBitWidth();
6164 // There might be negative interim results.
6165 if (Addend.isUnsigned()) {
6166 Addend = Addend.zext(++AddendBitWidth);
6167 Addend.setIsSigned(true);
6168 }
6169 // Adjust the bit width of the APSInts.
6170 if (AddendBitWidth > BitWidth) {
6171 Offset = Offset.sext(AddendBitWidth);
6172 BitWidth = AddendBitWidth;
6173 } else if (BitWidth > AddendBitWidth) {
6174 Addend = Addend.sext(BitWidth);
6175 }
6176
6177 bool Ov = false;
6178 llvm::APSInt ResOffset = Offset;
6179 if (BinOpKind == BO_Add)
6180 ResOffset = Offset.sadd_ov(Addend, Ov);
6181 else {
6182 assert(AddendIsRight && BinOpKind == BO_Sub &&
6183 "operator must be add or sub with addend on the right");
6184 ResOffset = Offset.ssub_ov(Addend, Ov);
6185 }
6186
6187 // We add an offset to a pointer here so we should support an offset as big as
6188 // possible.
6189 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006190 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6191 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00006192 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00006193 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6194 return;
6195 }
6196
6197 Offset = ResOffset;
6198}
6199
6200namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006201
Stephen Hines648c3692016-09-16 01:07:04 +00006202// This is a wrapper class around StringLiteral to support offsetted string
6203// literals as format strings. It takes the offset into account when returning
6204// the string and its length or the source locations to display notes correctly.
6205class FormatStringLiteral {
6206 const StringLiteral *FExpr;
6207 int64_t Offset;
6208
6209 public:
6210 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6211 : FExpr(fexpr), Offset(Offset) {}
6212
6213 StringRef getString() const {
6214 return FExpr->getString().drop_front(Offset);
6215 }
6216
6217 unsigned getByteLength() const {
6218 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6219 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006220
Stephen Hines648c3692016-09-16 01:07:04 +00006221 unsigned getLength() const { return FExpr->getLength() - Offset; }
6222 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6223
6224 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6225
6226 QualType getType() const { return FExpr->getType(); }
6227
6228 bool isAscii() const { return FExpr->isAscii(); }
6229 bool isWide() const { return FExpr->isWide(); }
6230 bool isUTF8() const { return FExpr->isUTF8(); }
6231 bool isUTF16() const { return FExpr->isUTF16(); }
6232 bool isUTF32() const { return FExpr->isUTF32(); }
6233 bool isPascal() const { return FExpr->isPascal(); }
6234
6235 SourceLocation getLocationOfByte(
6236 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6237 const TargetInfo &Target, unsigned *StartToken = nullptr,
6238 unsigned *StartTokenByteOffset = nullptr) const {
6239 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6240 StartToken, StartTokenByteOffset);
6241 }
6242
Stephen Kelly724e9e52018-08-09 20:05:03 +00006243 SourceLocation getBeginLoc() const LLVM_READONLY {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006244 return FExpr->getBeginLoc().getLocWithOffset(Offset);
Stephen Hines648c3692016-09-16 01:07:04 +00006245 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006246
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006247 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
Stephen Hines648c3692016-09-16 01:07:04 +00006248};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006249
6250} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00006251
6252static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006253 const Expr *OrigFormatExpr,
6254 ArrayRef<const Expr *> Args,
6255 bool HasVAListArg, unsigned format_idx,
6256 unsigned firstDataArg,
6257 Sema::FormatStringType Type,
6258 bool inFunctionCall,
6259 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006260 llvm::SmallBitVector &CheckedVarArgs,
6261 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006262
Richard Smith55ce3522012-06-25 20:30:08 +00006263// Determine if an expression is a string literal or constant string.
6264// If this function returns false on the arguments to a function expecting a
6265// format string, we will usually need to emit a warning.
6266// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00006267static StringLiteralCheckType
6268checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6269 bool HasVAListArg, unsigned format_idx,
6270 unsigned firstDataArg, Sema::FormatStringType Type,
6271 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006272 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006273 UncoveredArgHandler &UncoveredArg,
6274 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00006275 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00006276 assert(Offset.isSigned() && "invalid offset");
6277
Douglas Gregorc25f7662009-05-19 22:10:17 +00006278 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00006279 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006280
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006281 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00006282
Richard Smithd7293d72013-08-05 18:49:43 +00006283 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00006284 // Technically -Wformat-nonliteral does not warn about this case.
6285 // The behavior of printf and friends in this case is implementation
6286 // dependent. Ideally if the format string cannot be null then
6287 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00006288 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00006289
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006290 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00006291 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006292 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00006293 // The expression is a literal if both sub-expressions were, and it was
6294 // completely checked only if both sub-expressions were checked.
6295 const AbstractConditionalOperator *C =
6296 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006297
6298 // Determine whether it is necessary to check both sub-expressions, for
6299 // example, because the condition expression is a constant that can be
6300 // evaluated at compile time.
6301 bool CheckLeft = true, CheckRight = true;
6302
6303 bool Cond;
6304 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6305 if (Cond)
6306 CheckRight = false;
6307 else
6308 CheckLeft = false;
6309 }
6310
Stephen Hines648c3692016-09-16 01:07:04 +00006311 // We need to maintain the offsets for the right and the left hand side
6312 // separately to check if every possible indexed expression is a valid
6313 // string literal. They might have different offsets for different string
6314 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006315 StringLiteralCheckType Left;
6316 if (!CheckLeft)
6317 Left = SLCT_UncheckedLiteral;
6318 else {
6319 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6320 HasVAListArg, format_idx, firstDataArg,
6321 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00006322 CheckedVarArgs, UncoveredArg, Offset);
6323 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006324 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00006325 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006326 }
6327
Richard Smith55ce3522012-06-25 20:30:08 +00006328 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00006329 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006330 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006331 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006332 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006333
6334 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006335 }
6336
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006337 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00006338 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6339 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006340
John McCallc07a0c72011-02-17 10:25:35 +00006341 case Stmt::OpaqueValueExprClass:
6342 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6343 E = src;
6344 goto tryAgain;
6345 }
Richard Smith55ce3522012-06-25 20:30:08 +00006346 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00006347
Ted Kremeneka8890832011-02-24 23:03:04 +00006348 case Stmt::PredefinedExprClass:
6349 // While __func__, etc., are technically not string literals, they
6350 // cannot contain format specifiers and thus are not a security
6351 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00006352 return SLCT_UncheckedLiteral;
Fangrui Song6907ce22018-07-30 19:24:48 +00006353
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006354 case Stmt::DeclRefExprClass: {
6355 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006356
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006357 // As an exception, do not flag errors for variables binding to
6358 // const string literals.
6359 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6360 bool isConstant = false;
6361 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006362
Richard Smithd7293d72013-08-05 18:49:43 +00006363 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6364 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00006365 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00006366 isConstant = T.isConstant(S.Context) &&
6367 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00006368 } else if (T->isObjCObjectPointerType()) {
6369 // In ObjC, there is usually no "const ObjectPointer" type,
6370 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00006371 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006372 }
Mike Stump11289f42009-09-09 15:08:12 +00006373
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006374 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006375 if (const Expr *Init = VD->getAnyInitializer()) {
6376 // Look through initializers like const char c[] = { "foo" }
6377 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6378 if (InitList->isStringLiteralInit())
6379 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6380 }
Richard Smithd7293d72013-08-05 18:49:43 +00006381 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006382 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006383 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006384 /*InFunctionCall*/ false, CheckedVarArgs,
6385 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006386 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006387 }
Mike Stump11289f42009-09-09 15:08:12 +00006388
Anders Carlssonb012ca92009-06-28 19:55:58 +00006389 // For vprintf* functions (i.e., HasVAListArg==true), we add a
6390 // special check to see if the format string is a function parameter
6391 // of the function calling the printf function. If the function
6392 // has an attribute indicating it is a printf-like function, then we
6393 // should suppress warnings concerning non-literals being used in a call
6394 // to a vprintf function. For example:
6395 //
6396 // void
6397 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6398 // va_list ap;
6399 // va_start(ap, fmt);
6400 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
6401 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00006402 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006403 if (HasVAListArg) {
6404 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6405 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6406 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00006407 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006408 // adjust for implicit parameter
6409 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6410 if (MD->isInstance())
6411 ++PVIndex;
6412 // We also check if the formats are compatible.
6413 // We can't pass a 'scanf' string to a 'printf' function.
6414 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00006415 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00006416 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006417 }
6418 }
6419 }
6420 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006421 }
Mike Stump11289f42009-09-09 15:08:12 +00006422
Richard Smith55ce3522012-06-25 20:30:08 +00006423 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006424 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006425
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006426 case Stmt::CallExprClass:
6427 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006428 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006429 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
Michael Krusef18adbb2018-07-04 01:37:11 +00006430 bool IsFirst = true;
6431 StringLiteralCheckType CommonResult;
6432 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006433 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Michael Krusef18adbb2018-07-04 01:37:11 +00006434 StringLiteralCheckType Result = checkFormatStringExpr(
6435 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6436 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6437 if (IsFirst) {
6438 CommonResult = Result;
6439 IsFirst = false;
6440 }
6441 }
6442 if (!IsFirst)
6443 return CommonResult;
6444
6445 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006446 unsigned BuiltinID = FD->getBuiltinID();
6447 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6448 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6449 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00006450 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006451 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006452 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006453 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006454 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006455 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006456 }
6457 }
Mike Stump11289f42009-09-09 15:08:12 +00006458
Richard Smith55ce3522012-06-25 20:30:08 +00006459 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006460 }
Alex Lorenzd9007142016-10-24 09:42:34 +00006461 case Stmt::ObjCMessageExprClass: {
6462 const auto *ME = cast<ObjCMessageExpr>(E);
6463 if (const auto *ND = ME->getMethodDecl()) {
6464 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006465 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00006466 return checkFormatStringExpr(
6467 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6468 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6469 }
6470 }
6471
6472 return SLCT_NotALiteral;
6473 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006474 case Stmt::ObjCStringLiteralClass:
6475 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00006476 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006477
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006478 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006479 StrE = ObjCFExpr->getString();
6480 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006481 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006482
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006483 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00006484 if (Offset.isNegative() || Offset > StrE->getLength()) {
6485 // TODO: It would be better to have an explicit warning for out of
6486 // bounds literals.
6487 return SLCT_NotALiteral;
6488 }
6489 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6490 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006491 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006492 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00006493 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006494 }
Mike Stump11289f42009-09-09 15:08:12 +00006495
Richard Smith55ce3522012-06-25 20:30:08 +00006496 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006497 }
Stephen Hines648c3692016-09-16 01:07:04 +00006498 case Stmt::BinaryOperatorClass: {
Stephen Hines648c3692016-09-16 01:07:04 +00006499 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6500
6501 // A string literal + an int offset is still a string literal.
6502 if (BinOp->isAdditiveOp()) {
Fangrui Song407659a2018-11-30 23:41:18 +00006503 Expr::EvalResult LResult, RResult;
6504
Stephen Hines648c3692016-09-16 01:07:04 +00006505 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6506 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6507
6508 if (LIsInt != RIsInt) {
6509 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6510
6511 if (LIsInt) {
6512 if (BinOpKind == BO_Add) {
Fangrui Song407659a2018-11-30 23:41:18 +00006513 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00006514 E = BinOp->getRHS();
6515 goto tryAgain;
6516 }
6517 } else {
Fangrui Song407659a2018-11-30 23:41:18 +00006518 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00006519 E = BinOp->getLHS();
6520 goto tryAgain;
6521 }
6522 }
Stephen Hines648c3692016-09-16 01:07:04 +00006523 }
George Burgess IVd273aab2016-09-22 00:00:26 +00006524
6525 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00006526 }
6527 case Stmt::UnaryOperatorClass: {
6528 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6529 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006530 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Fangrui Song407659a2018-11-30 23:41:18 +00006531 Expr::EvalResult IndexResult;
Stephen Hines648c3692016-09-16 01:07:04 +00006532 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
Fangrui Song407659a2018-11-30 23:41:18 +00006533 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6534 /*RHS is int*/ true);
Stephen Hines648c3692016-09-16 01:07:04 +00006535 E = ASE->getBase();
6536 goto tryAgain;
6537 }
6538 }
6539
6540 return SLCT_NotALiteral;
6541 }
Mike Stump11289f42009-09-09 15:08:12 +00006542
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006543 default:
Richard Smith55ce3522012-06-25 20:30:08 +00006544 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006545 }
6546}
6547
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006548Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00006549 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00006550 .Case("scanf", FST_Scanf)
6551 .Cases("printf", "printf0", FST_Printf)
6552 .Cases("NSString", "CFString", FST_NSString)
6553 .Case("strftime", FST_Strftime)
6554 .Case("strfmon", FST_Strfmon)
6555 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6556 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6557 .Case("os_trace", FST_OSLog)
6558 .Case("os_log", FST_OSLog)
6559 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006560}
6561
Jordan Rose3e0ec582012-07-19 18:10:23 +00006562/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00006563/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00006564/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006565bool Sema::CheckFormatArguments(const FormatAttr *Format,
6566 ArrayRef<const Expr *> Args,
6567 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006568 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006569 SourceLocation Loc, SourceRange Range,
6570 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00006571 FormatStringInfo FSI;
6572 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006573 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00006574 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00006575 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00006576 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006577}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00006578
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006579bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006580 bool HasVAListArg, unsigned format_idx,
6581 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006582 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006583 SourceLocation Loc, SourceRange Range,
6584 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00006585 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006586 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006587 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00006588 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006589 }
Mike Stump11289f42009-09-09 15:08:12 +00006590
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006591 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006592
Chris Lattnerb87b1b32007-08-10 20:18:51 +00006593 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00006594 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006595 // Dynamically generated format strings are difficult to
6596 // automatically vet at compile time. Requiring that format strings
6597 // are string literals: (1) permits the checking of format strings by
6598 // the compiler and thereby (2) can practically remove the source of
6599 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00006600
Mike Stump11289f42009-09-09 15:08:12 +00006601 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00006602 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00006603 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00006604 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006605 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00006606 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00006607 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6608 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006609 /*IsFunctionCall*/ true, CheckedVarArgs,
6610 UncoveredArg,
6611 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006612
6613 // Generate a diagnostic where an uncovered argument is detected.
6614 if (UncoveredArg.hasUncoveredArg()) {
6615 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6616 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6617 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6618 }
6619
Richard Smith55ce3522012-06-25 20:30:08 +00006620 if (CT != SLCT_NotALiteral)
6621 // Literal format string found, check done!
6622 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00006623
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006624 // Strftime is particular as it always uses a single 'time' argument,
6625 // so it is safe to pass a non-literal string.
6626 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00006627 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006628
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006629 // Do not emit diag when the string param is a macro expansion and the
6630 // format is either NSString or CFString. This is a hack to prevent
6631 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6632 // which are usually used in place of NS and CF string literals.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006633 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006634 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00006635 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006636
Chris Lattnercc5d1c22009-04-29 04:59:47 +00006637 // If there are no arguments specified, warn with -Wformat-security, otherwise
6638 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006639 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00006640 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6641 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006642 switch (Type) {
6643 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006644 break;
6645 case FST_Kprintf:
6646 case FST_FreeBSDKPrintf:
6647 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00006648 Diag(FormatLoc, diag::note_format_security_fixit)
6649 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006650 break;
6651 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00006652 Diag(FormatLoc, diag::note_format_security_fixit)
6653 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006654 break;
6655 }
6656 } else {
6657 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00006658 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006659 }
Richard Smith55ce3522012-06-25 20:30:08 +00006660 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006661}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006662
Ted Kremenekab278de2010-01-28 23:39:18 +00006663namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006664
Ted Kremenek02087932010-07-16 02:11:22 +00006665class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6666protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00006667 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00006668 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00006669 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006670 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00006671 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00006672 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00006673 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00006674 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006675 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00006676 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00006677 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006678 bool usesPositionalArgs = false;
6679 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006680 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00006681 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00006682 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006683 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006684
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006685public:
Stephen Hines648c3692016-09-16 01:07:04 +00006686 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006687 const Expr *origFormatExpr,
6688 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006689 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006690 ArrayRef<const Expr *> Args, unsigned formatIdx,
6691 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006692 llvm::SmallBitVector &CheckedVarArgs,
6693 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006694 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6695 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6696 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00006697 inFunctionCall(inFunctionCall), CallType(callType),
6698 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00006699 CoveredArgs.resize(numDataArgs);
6700 CoveredArgs.reset();
6701 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006702
Ted Kremenek019d2242010-01-29 01:50:07 +00006703 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006704
Ted Kremenek02087932010-07-16 02:11:22 +00006705 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006706 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006707
Jordan Rose92303592012-09-08 04:00:03 +00006708 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00006709 const analyze_format_string::FormatSpecifier &FS,
6710 const analyze_format_string::ConversionSpecifier &CS,
6711 const char *startSpecifier, unsigned specifierLen,
6712 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00006713
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006714 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00006715 const analyze_format_string::FormatSpecifier &FS,
6716 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006717
6718 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00006719 const analyze_format_string::ConversionSpecifier &CS,
6720 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006721
Craig Toppere14c0f82014-03-12 04:55:44 +00006722 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00006723
Craig Toppere14c0f82014-03-12 04:55:44 +00006724 void HandleInvalidPosition(const char *startSpecifier,
6725 unsigned specifierLen,
6726 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00006727
Craig Toppere14c0f82014-03-12 04:55:44 +00006728 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00006729
Craig Toppere14c0f82014-03-12 04:55:44 +00006730 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006731
Richard Trieu03cf7b72011-10-28 00:41:25 +00006732 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00006733 static void
6734 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6735 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6736 bool IsStringLocation, Range StringRange,
6737 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00006738
Ted Kremenek02087932010-07-16 02:11:22 +00006739protected:
Ted Kremenekce815422010-07-19 21:25:57 +00006740 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6741 const char *startSpec,
6742 unsigned specifierLen,
6743 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00006744
6745 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6746 const char *startSpec,
6747 unsigned specifierLen);
Fangrui Song6907ce22018-07-30 19:24:48 +00006748
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006749 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00006750 CharSourceRange getSpecifierRange(const char *startSpecifier,
6751 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00006752 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006753
Ted Kremenek5739de72010-01-29 01:06:55 +00006754 const Expr *getDataArg(unsigned i) const;
Fangrui Song6907ce22018-07-30 19:24:48 +00006755
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006756 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6757 const analyze_format_string::ConversionSpecifier &CS,
6758 const char *startSpecifier, unsigned specifierLen,
6759 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00006760
6761 template <typename Range>
6762 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6763 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006764 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00006765};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006766
6767} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006768
Ted Kremenek02087932010-07-16 02:11:22 +00006769SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00006770 return OrigFormatExpr->getSourceRange();
6771}
6772
Ted Kremenek02087932010-07-16 02:11:22 +00006773CharSourceRange CheckFormatHandler::
6774getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00006775 SourceLocation Start = getLocationOfByte(startSpecifier);
6776 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
6777
6778 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00006779 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00006780
6781 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006782}
6783
Ted Kremenek02087932010-07-16 02:11:22 +00006784SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00006785 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6786 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00006787}
6788
Ted Kremenek02087932010-07-16 02:11:22 +00006789void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6790 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00006791 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6792 getLocationOfByte(startSpecifier),
6793 /*IsStringLocation*/true,
6794 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00006795}
6796
Jordan Rose92303592012-09-08 04:00:03 +00006797void CheckFormatHandler::HandleInvalidLengthModifier(
6798 const analyze_format_string::FormatSpecifier &FS,
6799 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00006800 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00006801 using namespace analyze_format_string;
6802
6803 const LengthModifier &LM = FS.getLengthModifier();
6804 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6805
6806 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00006807 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00006808 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00006809 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00006810 getLocationOfByte(LM.getStart()),
6811 /*IsStringLocation*/true,
6812 getSpecifierRange(startSpecifier, specifierLen));
6813
6814 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6815 << FixedLM->toString()
6816 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6817
6818 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00006819 FixItHint Hint;
6820 if (DiagID == diag::warn_format_nonsensical_length)
6821 Hint = FixItHint::CreateRemoval(LMRange);
6822
6823 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00006824 getLocationOfByte(LM.getStart()),
6825 /*IsStringLocation*/true,
6826 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00006827 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00006828 }
6829}
6830
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006831void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00006832 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006833 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00006834 using namespace analyze_format_string;
6835
6836 const LengthModifier &LM = FS.getLengthModifier();
6837 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6838
6839 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00006840 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00006841 if (FixedLM) {
6842 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6843 << LM.toString() << 0,
6844 getLocationOfByte(LM.getStart()),
6845 /*IsStringLocation*/true,
6846 getSpecifierRange(startSpecifier, specifierLen));
6847
6848 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6849 << FixedLM->toString()
6850 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6851
6852 } else {
6853 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6854 << LM.toString() << 0,
6855 getLocationOfByte(LM.getStart()),
6856 /*IsStringLocation*/true,
6857 getSpecifierRange(startSpecifier, specifierLen));
6858 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006859}
6860
6861void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6862 const analyze_format_string::ConversionSpecifier &CS,
6863 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00006864 using namespace analyze_format_string;
6865
6866 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00006867 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00006868 if (FixedCS) {
6869 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6870 << CS.toString() << /*conversion specifier*/1,
6871 getLocationOfByte(CS.getStart()),
6872 /*IsStringLocation*/true,
6873 getSpecifierRange(startSpecifier, specifierLen));
6874
6875 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6876 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6877 << FixedCS->toString()
6878 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6879 } else {
6880 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6881 << CS.toString() << /*conversion specifier*/1,
6882 getLocationOfByte(CS.getStart()),
6883 /*IsStringLocation*/true,
6884 getSpecifierRange(startSpecifier, specifierLen));
6885 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006886}
6887
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00006888void CheckFormatHandler::HandlePosition(const char *startPos,
6889 unsigned posLen) {
6890 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6891 getLocationOfByte(startPos),
6892 /*IsStringLocation*/true,
6893 getSpecifierRange(startPos, posLen));
6894}
6895
Ted Kremenekd1668192010-02-27 01:41:03 +00006896void
Ted Kremenek02087932010-07-16 02:11:22 +00006897CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
6898 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006899 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
6900 << (unsigned) p,
6901 getLocationOfByte(startPos), /*IsStringLocation*/true,
6902 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00006903}
6904
Ted Kremenek02087932010-07-16 02:11:22 +00006905void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00006906 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006907 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6908 getLocationOfByte(startPos),
6909 /*IsStringLocation*/true,
6910 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00006911}
6912
Ted Kremenek02087932010-07-16 02:11:22 +00006913void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006914 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00006915 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006916 EmitFormatDiagnostic(
6917 S.PDiag(diag::warn_printf_format_string_contains_null_char),
6918 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6919 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00006920 }
Ted Kremenek02087932010-07-16 02:11:22 +00006921}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006922
Jordan Rose58bbe422012-07-19 18:10:08 +00006923// Note that this may return NULL if there was an error parsing or building
6924// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00006925const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006926 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00006927}
6928
6929void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006930 // Does the number of data arguments exceed the number of
6931 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00006932 if (!HasVAListArg) {
6933 // Find any arguments that weren't covered.
6934 CoveredArgs.flip();
6935 signed notCoveredArg = CoveredArgs.find_first();
6936 if (notCoveredArg >= 0) {
6937 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006938 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6939 } else {
6940 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00006941 }
6942 }
6943}
6944
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006945void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6946 const Expr *ArgExpr) {
6947 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6948 "Invalid state");
6949
6950 if (!ArgExpr)
6951 return;
6952
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006953 SourceLocation Loc = ArgExpr->getBeginLoc();
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006954
6955 if (S.getSourceManager().isInSystemMacro(Loc))
6956 return;
6957
6958 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6959 for (auto E : DiagnosticExprs)
6960 PDiag << E->getSourceRange();
6961
6962 CheckFormatHandler::EmitFormatDiagnostic(
6963 S, IsFunctionCall, DiagnosticExprs[0],
6964 PDiag, Loc, /*IsStringLocation*/false,
6965 DiagnosticExprs[0]->getSourceRange());
6966}
6967
Ted Kremenekce815422010-07-19 21:25:57 +00006968bool
6969CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6970 SourceLocation Loc,
6971 const char *startSpec,
6972 unsigned specifierLen,
6973 const char *csStart,
6974 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00006975 bool keepGoing = true;
6976 if (argIndex < NumDataArgs) {
6977 // Consider the argument coverered, even though the specifier doesn't
6978 // make sense.
6979 CoveredArgs.set(argIndex);
6980 }
6981 else {
6982 // If argIndex exceeds the number of data arguments we
6983 // don't issue a warning because that is just a cascade of warnings (and
6984 // they may have intended '%%' anyway). We don't want to continue processing
6985 // the format string after this point, however, as we will like just get
6986 // gibberish when trying to match arguments.
6987 keepGoing = false;
6988 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006989
6990 StringRef Specifier(csStart, csLen);
6991
6992 // If the specifier in non-printable, it could be the first byte of a UTF-8
6993 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6994 // hex value.
6995 std::string CodePointStr;
6996 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00006997 llvm::UTF32 CodePoint;
6998 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6999 const llvm::UTF8 *E =
7000 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7001 llvm::ConversionResult Result =
7002 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007003
Justin Lebar90910552016-09-30 00:38:45 +00007004 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007005 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00007006 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007007 }
7008
7009 llvm::raw_string_ostream OS(CodePointStr);
7010 if (CodePoint < 256)
7011 OS << "\\x" << llvm::format("%02x", CodePoint);
7012 else if (CodePoint <= 0xFFFF)
7013 OS << "\\u" << llvm::format("%04x", CodePoint);
7014 else
7015 OS << "\\U" << llvm::format("%08x", CodePoint);
7016 OS.flush();
7017 Specifier = CodePointStr;
7018 }
7019
7020 EmitFormatDiagnostic(
7021 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7022 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7023
Ted Kremenekce815422010-07-19 21:25:57 +00007024 return keepGoing;
7025}
7026
Richard Trieu03cf7b72011-10-28 00:41:25 +00007027void
7028CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7029 const char *startSpec,
7030 unsigned specifierLen) {
7031 EmitFormatDiagnostic(
7032 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7033 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7034}
7035
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007036bool
7037CheckFormatHandler::CheckNumArgs(
7038 const analyze_format_string::FormatSpecifier &FS,
7039 const analyze_format_string::ConversionSpecifier &CS,
7040 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7041
7042 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007043 PartialDiagnostic PDiag = FS.usesPositionalArg()
7044 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7045 << (argIndex+1) << NumDataArgs)
7046 : S.PDiag(diag::warn_printf_insufficient_data_args);
7047 EmitFormatDiagnostic(
7048 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7049 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007050
7051 // Since more arguments than conversion tokens are given, by extension
7052 // all arguments are covered, so mark this as so.
7053 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007054 return false;
7055 }
7056 return true;
7057}
7058
Richard Trieu03cf7b72011-10-28 00:41:25 +00007059template<typename Range>
7060void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7061 SourceLocation Loc,
7062 bool IsStringLocation,
7063 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00007064 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007065 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00007066 Loc, IsStringLocation, StringRange, FixIt);
7067}
7068
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007069/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00007070/// so that the function call and string are in diagnostic messages.
7071///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007072/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00007073/// call and only one diagnostic message will be produced. Otherwise, an
7074/// extra note will be emitted pointing to location of the format string.
7075///
7076/// \param ArgumentExpr the expression that is passed as the format string
7077/// argument in the function call. Used for getting locations when two
7078/// diagnostics are emitted.
7079///
7080/// \param PDiag the callee should already have provided any strings for the
7081/// diagnostic message. This function only adds locations and fixits
7082/// to diagnostics.
7083///
7084/// \param Loc primary location for diagnostic. If two diagnostics are
7085/// required, one will be at Loc and a new SourceLocation will be created for
7086/// the other one.
7087///
7088/// \param IsStringLocation if true, Loc points to the format string should be
7089/// used for the note. Otherwise, Loc points to the argument list and will
7090/// be used with PDiag.
7091///
7092/// \param StringRange some or all of the string to highlight. This is
7093/// templated so it can accept either a CharSourceRange or a SourceRange.
7094///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007095/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00007096template <typename Range>
7097void CheckFormatHandler::EmitFormatDiagnostic(
7098 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7099 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7100 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00007101 if (InFunctionCall) {
7102 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7103 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007104 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00007105 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007106 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7107 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00007108
7109 const Sema::SemaDiagnosticBuilder &Note =
7110 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7111 diag::note_format_string_defined);
7112
7113 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007114 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00007115 }
7116}
7117
Ted Kremenek02087932010-07-16 02:11:22 +00007118//===--- CHECK: Printf format string checking ------------------------------===//
7119
7120namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007121
Ted Kremenek02087932010-07-16 02:11:22 +00007122class CheckPrintfHandler : public CheckFormatHandler {
7123public:
Stephen Hines648c3692016-09-16 01:07:04 +00007124 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007125 const Expr *origFormatExpr,
7126 const Sema::FormatStringType type, unsigned firstDataArg,
7127 unsigned numDataArgs, bool isObjC, const char *beg,
7128 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00007129 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00007130 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007131 llvm::SmallBitVector &CheckedVarArgs,
7132 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007133 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7134 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7135 inFunctionCall, CallType, CheckedVarArgs,
7136 UncoveredArg) {}
7137
7138 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7139
7140 /// Returns true if '%@' specifiers are allowed in the format string.
7141 bool allowsObjCArg() const {
7142 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7143 FSType == Sema::FST_OSTrace;
7144 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00007145
Ted Kremenek02087932010-07-16 02:11:22 +00007146 bool HandleInvalidPrintfConversionSpecifier(
7147 const analyze_printf::PrintfSpecifier &FS,
7148 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007149 unsigned specifierLen) override;
7150
Akira Hatanakad572cf42018-11-06 07:05:14 +00007151 void handleInvalidMaskType(StringRef MaskType) override;
7152
Ted Kremenek02087932010-07-16 02:11:22 +00007153 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7154 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007155 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007156 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7157 const char *StartSpecifier,
7158 unsigned SpecifierLen,
7159 const Expr *E);
7160
Ted Kremenek02087932010-07-16 02:11:22 +00007161 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7162 const char *startSpecifier, unsigned specifierLen);
7163 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7164 const analyze_printf::OptionalAmount &Amt,
7165 unsigned type,
7166 const char *startSpecifier, unsigned specifierLen);
7167 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7168 const analyze_printf::OptionalFlag &flag,
7169 const char *startSpecifier, unsigned specifierLen);
7170 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7171 const analyze_printf::OptionalFlag &ignoredFlag,
7172 const analyze_printf::OptionalFlag &flag,
7173 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007174 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00007175 const Expr *E);
Fangrui Song6907ce22018-07-30 19:24:48 +00007176
Ted Kremenek2b417712015-07-02 05:39:16 +00007177 void HandleEmptyObjCModifierFlag(const char *startFlag,
7178 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007179
Ted Kremenek2b417712015-07-02 05:39:16 +00007180 void HandleInvalidObjCModifierFlag(const char *startFlag,
7181 unsigned flagLen) override;
7182
7183 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7184 const char *flagsEnd,
Fangrui Song6907ce22018-07-30 19:24:48 +00007185 const char *conversionPosition)
Ted Kremenek2b417712015-07-02 05:39:16 +00007186 override;
7187};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007188
7189} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00007190
7191bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7192 const analyze_printf::PrintfSpecifier &FS,
7193 const char *startSpecifier,
7194 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007195 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007196 FS.getConversionSpecifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00007197
Ted Kremenekce815422010-07-19 21:25:57 +00007198 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7199 getLocationOfByte(CS.getStart()),
7200 startSpecifier, specifierLen,
7201 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00007202}
7203
Akira Hatanakad572cf42018-11-06 07:05:14 +00007204void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7205 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7206}
7207
Ted Kremenek02087932010-07-16 02:11:22 +00007208bool CheckPrintfHandler::HandleAmount(
7209 const analyze_format_string::OptionalAmount &Amt,
7210 unsigned k, const char *startSpecifier,
7211 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007212 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007213 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00007214 unsigned argIndex = Amt.getArgIndex();
7215 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007216 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7217 << k,
7218 getLocationOfByte(Amt.getStart()),
7219 /*IsStringLocation*/true,
7220 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007221 // Don't do any more checking. We will just emit
7222 // spurious errors.
7223 return false;
7224 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007225
Ted Kremenek5739de72010-01-29 01:06:55 +00007226 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00007227 // Although not in conformance with C99, we also allow the argument to be
7228 // an 'unsigned int' as that is a reasonably safe case. GCC also
7229 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00007230 CoveredArgs.set(argIndex);
7231 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007232 if (!Arg)
7233 return false;
7234
Ted Kremenek5739de72010-01-29 01:06:55 +00007235 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007236
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007237 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7238 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007239
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007240 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007241 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007242 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00007243 << T << Arg->getSourceRange(),
7244 getLocationOfByte(Amt.getStart()),
7245 /*IsStringLocation*/true,
7246 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007247 // Don't do any more checking. We will just emit
7248 // spurious errors.
7249 return false;
7250 }
7251 }
7252 }
7253 return true;
7254}
Ted Kremenek5739de72010-01-29 01:06:55 +00007255
Tom Careb49ec692010-06-17 19:00:27 +00007256void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00007257 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007258 const analyze_printf::OptionalAmount &Amt,
7259 unsigned type,
7260 const char *startSpecifier,
7261 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007262 const analyze_printf::PrintfConversionSpecifier &CS =
7263 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00007264
Richard Trieu03cf7b72011-10-28 00:41:25 +00007265 FixItHint fixit =
7266 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7267 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7268 Amt.getConstantLength()))
7269 : FixItHint();
7270
7271 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7272 << type << CS.toString(),
7273 getLocationOfByte(Amt.getStart()),
7274 /*IsStringLocation*/true,
7275 getSpecifierRange(startSpecifier, specifierLen),
7276 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00007277}
7278
Ted Kremenek02087932010-07-16 02:11:22 +00007279void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007280 const analyze_printf::OptionalFlag &flag,
7281 const char *startSpecifier,
7282 unsigned specifierLen) {
7283 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007284 const analyze_printf::PrintfConversionSpecifier &CS =
7285 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00007286 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7287 << flag.toString() << CS.toString(),
7288 getLocationOfByte(flag.getPosition()),
7289 /*IsStringLocation*/true,
7290 getSpecifierRange(startSpecifier, specifierLen),
7291 FixItHint::CreateRemoval(
7292 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007293}
7294
7295void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00007296 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007297 const analyze_printf::OptionalFlag &ignoredFlag,
7298 const analyze_printf::OptionalFlag &flag,
7299 const char *startSpecifier,
7300 unsigned specifierLen) {
7301 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00007302 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7303 << ignoredFlag.toString() << flag.toString(),
7304 getLocationOfByte(ignoredFlag.getPosition()),
7305 /*IsStringLocation*/true,
7306 getSpecifierRange(startSpecifier, specifierLen),
7307 FixItHint::CreateRemoval(
7308 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007309}
7310
Ted Kremenek2b417712015-07-02 05:39:16 +00007311void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7312 unsigned flagLen) {
7313 // Warn about an empty flag.
7314 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7315 getLocationOfByte(startFlag),
7316 /*IsStringLocation*/true,
7317 getSpecifierRange(startFlag, flagLen));
7318}
7319
7320void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7321 unsigned flagLen) {
7322 // Warn about an invalid flag.
7323 auto Range = getSpecifierRange(startFlag, flagLen);
7324 StringRef flag(startFlag, flagLen);
7325 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7326 getLocationOfByte(startFlag),
7327 /*IsStringLocation*/true,
7328 Range, FixItHint::CreateRemoval(Range));
7329}
7330
7331void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7332 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7333 // Warn about using '[...]' without a '@' conversion.
7334 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7335 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7336 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7337 getLocationOfByte(conversionPosition),
7338 /*IsStringLocation*/true,
7339 Range, FixItHint::CreateRemoval(Range));
7340}
7341
Richard Smith55ce3522012-06-25 20:30:08 +00007342// Determines if the specified is a C++ class or struct containing
7343// a member with the specified name and kind (e.g. a CXXMethodDecl named
7344// "c_str()").
7345template<typename MemberKind>
7346static llvm::SmallPtrSet<MemberKind*, 1>
7347CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7348 const RecordType *RT = Ty->getAs<RecordType>();
7349 llvm::SmallPtrSet<MemberKind*, 1> Results;
7350
7351 if (!RT)
7352 return Results;
7353 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00007354 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00007355 return Results;
7356
Alp Tokerb6cc5922014-05-03 03:45:55 +00007357 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00007358 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00007359 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00007360
7361 // We just need to include all members of the right kind turned up by the
7362 // filter, at this point.
7363 if (S.LookupQualifiedName(R, RT->getDecl()))
7364 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7365 NamedDecl *decl = (*I)->getUnderlyingDecl();
7366 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7367 Results.insert(FK);
7368 }
7369 return Results;
7370}
7371
Richard Smith2868a732014-02-28 01:36:39 +00007372/// Check if we could call '.c_str()' on an object.
7373///
7374/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7375/// allow the call, or if it would be ambiguous).
7376bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007377 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7378
Richard Smith2868a732014-02-28 01:36:39 +00007379 MethodSet Results =
7380 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7381 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7382 MI != ME; ++MI)
7383 if ((*MI)->getMinRequiredArguments() == 0)
7384 return true;
7385 return false;
7386}
7387
Richard Smith55ce3522012-06-25 20:30:08 +00007388// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007389// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00007390// Returns true when a c_str() conversion method is found.
7391bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00007392 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007393 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00007394
7395 MethodSet Results =
7396 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7397
7398 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7399 MI != ME; ++MI) {
7400 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00007401 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00007402 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00007403 // FIXME: Suggest parens if the expression needs them.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007404 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007405 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7406 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
Richard Smith55ce3522012-06-25 20:30:08 +00007407 return true;
7408 }
7409 }
7410
7411 return false;
7412}
7413
Ted Kremenekab278de2010-01-28 23:39:18 +00007414bool
Ted Kremenek02087932010-07-16 02:11:22 +00007415CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00007416 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00007417 const char *startSpecifier,
7418 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007419 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007420 using namespace analyze_printf;
7421
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007422 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00007423
Ted Kremenek6cd69422010-07-19 22:01:06 +00007424 if (FS.consumesDataArgument()) {
7425 if (atFirstArg) {
7426 atFirstArg = false;
7427 usesPositionalArgs = FS.usesPositionalArg();
7428 }
7429 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007430 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7431 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007432 return false;
7433 }
Ted Kremenek5739de72010-01-29 01:06:55 +00007434 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007435
Ted Kremenekd1668192010-02-27 01:41:03 +00007436 // First check if the field width, precision, and conversion specifier
7437 // have matching data arguments.
7438 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7439 startSpecifier, specifierLen)) {
7440 return false;
7441 }
7442
7443 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7444 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007445 return false;
7446 }
7447
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007448 if (!CS.consumesDataArgument()) {
7449 // FIXME: Technically specifying a precision or field width here
7450 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00007451 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007452 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007453
Ted Kremenek4a49d982010-02-26 19:18:41 +00007454 // Consume the argument.
7455 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00007456 if (argIndex < NumDataArgs) {
7457 // The check to see if the argIndex is valid will come later.
7458 // We set the bit here because we may exit early from this
7459 // function if we encounter some other error.
7460 CoveredArgs.set(argIndex);
7461 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00007462
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007463 // FreeBSD kernel extensions.
7464 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7465 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7466 // We need at least two arguments.
7467 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7468 return false;
7469
7470 // Claim the second argument.
7471 CoveredArgs.set(argIndex + 1);
7472
7473 // Type check the first argument (int for %b, pointer for %D)
7474 const Expr *Ex = getDataArg(argIndex);
7475 const analyze_printf::ArgType &AT =
7476 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7477 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7478 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7479 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007480 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7481 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7482 << false << Ex->getSourceRange(),
7483 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7484 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007485
7486 // Type check the second argument (char * for both %b and %D)
7487 Ex = getDataArg(argIndex + 1);
7488 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7489 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7490 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007491 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7492 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7493 << false << Ex->getSourceRange(),
7494 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7495 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007496
7497 return true;
7498 }
7499
Ted Kremenek4a49d982010-02-26 19:18:41 +00007500 // Check for using an Objective-C specific conversion specifier
7501 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00007502 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00007503 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7504 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00007505 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007506
Mehdi Amini06d367c2016-10-24 20:39:34 +00007507 // %P can only be used with os_log.
7508 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7509 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7510 specifierLen);
7511 }
7512
7513 // %n is not allowed with os_log.
7514 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7515 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7516 getLocationOfByte(CS.getStart()),
7517 /*IsStringLocation*/ false,
7518 getSpecifierRange(startSpecifier, specifierLen));
7519
7520 return true;
7521 }
7522
7523 // Only scalars are allowed for os_trace.
7524 if (FSType == Sema::FST_OSTrace &&
7525 (CS.getKind() == ConversionSpecifier::PArg ||
7526 CS.getKind() == ConversionSpecifier::sArg ||
7527 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7528 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7529 specifierLen);
7530 }
7531
7532 // Check for use of public/private annotation outside of os_log().
7533 if (FSType != Sema::FST_OSLog) {
7534 if (FS.isPublic().isSet()) {
7535 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7536 << "public",
7537 getLocationOfByte(FS.isPublic().getPosition()),
7538 /*IsStringLocation*/ false,
7539 getSpecifierRange(startSpecifier, specifierLen));
7540 }
7541 if (FS.isPrivate().isSet()) {
7542 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7543 << "private",
7544 getLocationOfByte(FS.isPrivate().getPosition()),
7545 /*IsStringLocation*/ false,
7546 getSpecifierRange(startSpecifier, specifierLen));
7547 }
7548 }
7549
Tom Careb49ec692010-06-17 19:00:27 +00007550 // Check for invalid use of field width
7551 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00007552 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00007553 startSpecifier, specifierLen);
7554 }
7555
7556 // Check for invalid use of precision
7557 if (!FS.hasValidPrecision()) {
7558 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7559 startSpecifier, specifierLen);
7560 }
7561
Mehdi Amini06d367c2016-10-24 20:39:34 +00007562 // Precision is mandatory for %P specifier.
7563 if (CS.getKind() == ConversionSpecifier::PArg &&
7564 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7565 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7566 getLocationOfByte(startSpecifier),
7567 /*IsStringLocation*/ false,
7568 getSpecifierRange(startSpecifier, specifierLen));
7569 }
7570
Tom Careb49ec692010-06-17 19:00:27 +00007571 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00007572 if (!FS.hasValidThousandsGroupingPrefix())
7573 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007574 if (!FS.hasValidLeadingZeros())
7575 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7576 if (!FS.hasValidPlusPrefix())
7577 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00007578 if (!FS.hasValidSpacePrefix())
7579 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007580 if (!FS.hasValidAlternativeForm())
7581 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7582 if (!FS.hasValidLeftJustified())
7583 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7584
7585 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00007586 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7587 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7588 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007589 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7590 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7591 startSpecifier, specifierLen);
7592
7593 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007594 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007595 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7596 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007597 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007598 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007599 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007600 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7601 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00007602
Jordan Rose92303592012-09-08 04:00:03 +00007603 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7604 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7605
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007606 // The remaining checks depend on the data arguments.
7607 if (HasVAListArg)
7608 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007609
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007610 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007611 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007612
Jordan Rose58bbe422012-07-19 18:10:08 +00007613 const Expr *Arg = getDataArg(argIndex);
7614 if (!Arg)
7615 return true;
7616
7617 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00007618}
7619
Jordan Roseaee34382012-09-05 22:56:26 +00007620static bool requiresParensToAddCast(const Expr *E) {
7621 // FIXME: We should have a general way to reason about operator
7622 // precedence and whether parens are actually needed here.
7623 // Take care of a few common cases where they aren't.
7624 const Expr *Inside = E->IgnoreImpCasts();
7625 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7626 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7627
7628 switch (Inside->getStmtClass()) {
7629 case Stmt::ArraySubscriptExprClass:
7630 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007631 case Stmt::CharacterLiteralClass:
7632 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007633 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007634 case Stmt::FloatingLiteralClass:
7635 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007636 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007637 case Stmt::ObjCArrayLiteralClass:
7638 case Stmt::ObjCBoolLiteralExprClass:
7639 case Stmt::ObjCBoxedExprClass:
7640 case Stmt::ObjCDictionaryLiteralClass:
7641 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007642 case Stmt::ObjCIvarRefExprClass:
7643 case Stmt::ObjCMessageExprClass:
7644 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007645 case Stmt::ObjCStringLiteralClass:
7646 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007647 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007648 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007649 case Stmt::UnaryOperatorClass:
7650 return false;
7651 default:
7652 return true;
7653 }
7654}
7655
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007656static std::pair<QualType, StringRef>
7657shouldNotPrintDirectly(const ASTContext &Context,
7658 QualType IntendedTy,
7659 const Expr *E) {
7660 // Use a 'while' to peel off layers of typedefs.
7661 QualType TyTy = IntendedTy;
7662 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7663 StringRef Name = UserTy->getDecl()->getName();
7664 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00007665 .Case("CFIndex", Context.getNSIntegerType())
7666 .Case("NSInteger", Context.getNSIntegerType())
7667 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007668 .Case("SInt32", Context.IntTy)
7669 .Case("UInt32", Context.UnsignedIntTy)
7670 .Default(QualType());
7671
7672 if (!CastTy.isNull())
7673 return std::make_pair(CastTy, Name);
7674
7675 TyTy = UserTy->desugar();
7676 }
7677
7678 // Strip parens if necessary.
7679 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7680 return shouldNotPrintDirectly(Context,
7681 PE->getSubExpr()->getType(),
7682 PE->getSubExpr());
7683
7684 // If this is a conditional expression, then its result type is constructed
7685 // via usual arithmetic conversions and thus there might be no necessary
7686 // typedef sugar there. Recurse to operands to check for NSInteger &
7687 // Co. usage condition.
7688 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7689 QualType TrueTy, FalseTy;
7690 StringRef TrueName, FalseName;
7691
7692 std::tie(TrueTy, TrueName) =
7693 shouldNotPrintDirectly(Context,
7694 CO->getTrueExpr()->getType(),
7695 CO->getTrueExpr());
7696 std::tie(FalseTy, FalseName) =
7697 shouldNotPrintDirectly(Context,
7698 CO->getFalseExpr()->getType(),
7699 CO->getFalseExpr());
7700
7701 if (TrueTy == FalseTy)
7702 return std::make_pair(TrueTy, TrueName);
7703 else if (TrueTy.isNull())
7704 return std::make_pair(FalseTy, FalseName);
7705 else if (FalseTy.isNull())
7706 return std::make_pair(TrueTy, TrueName);
7707 }
7708
7709 return std::make_pair(QualType(), StringRef());
7710}
7711
Richard Smith55ce3522012-06-25 20:30:08 +00007712bool
7713CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7714 const char *StartSpecifier,
7715 unsigned SpecifierLen,
7716 const Expr *E) {
7717 using namespace analyze_format_string;
7718 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007719
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007720 // Now type check the data expression that matches the
7721 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00007722 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00007723 if (!AT.isValid())
7724 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00007725
Jordan Rose598ec092012-12-05 18:44:40 +00007726 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00007727 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7728 ExprTy = TET->getUnderlyingExpr()->getType();
7729 }
7730
JF Bastienec7d7f32018-06-22 21:54:40 +00007731 const analyze_printf::ArgType::MatchKind Match =
7732 AT.matchesType(S.Context, ExprTy);
7733 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7734 if (Match == analyze_printf::ArgType::Match)
Jordan Rose22b74712012-09-05 22:56:19 +00007735 return true;
Jordan Rose98709982012-06-04 22:48:57 +00007736
Jordan Rose22b74712012-09-05 22:56:19 +00007737 // Look through argument promotions for our error message's reported type.
7738 // This includes the integral and floating promotions, but excludes array
7739 // and function pointer decay; seeing that an argument intended to be a
7740 // string has type 'char [6]' is probably more confusing than 'char *'.
7741 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7742 if (ICE->getCastKind() == CK_IntegralCast ||
7743 ICE->getCastKind() == CK_FloatingCast) {
7744 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00007745 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00007746
7747 // Check if we didn't match because of an implicit cast from a 'char'
7748 // or 'short' to an 'int'. This is done because printf is a varargs
7749 // function.
7750 if (ICE->getType() == S.Context.IntTy ||
7751 ICE->getType() == S.Context.UnsignedIntTy) {
7752 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00007753 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00007754 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00007755 }
Jordan Rose98709982012-06-04 22:48:57 +00007756 }
Jordan Rose598ec092012-12-05 18:44:40 +00007757 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7758 // Special case for 'a', which has type 'int' in C.
7759 // Note, however, that we do /not/ want to treat multibyte constants like
7760 // 'MooV' as characters! This form is deprecated but still exists.
7761 if (ExprTy == S.Context.IntTy)
7762 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7763 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00007764 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007765
Jordan Rosebc53ed12014-05-31 04:12:14 +00007766 // Look through enums to their underlying type.
7767 bool IsEnum = false;
7768 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7769 ExprTy = EnumTy->getDecl()->getIntegerType();
7770 IsEnum = true;
7771 }
7772
Jordan Rose0e5badd2012-12-05 18:44:49 +00007773 // %C in an Objective-C context prints a unichar, not a wchar_t.
7774 // If the argument is an integer of some kind, believe the %C and suggest
7775 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00007776 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00007777 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00007778 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7779 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7780 !ExprTy->isCharType()) {
7781 // 'unichar' is defined as a typedef of unsigned short, but we should
7782 // prefer using the typedef if it is visible.
7783 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00007784
7785 // While we are here, check if the value is an IntegerLiteral that happens
7786 // to be within the valid range.
7787 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7788 const llvm::APInt &V = IL->getValue();
7789 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7790 return true;
7791 }
7792
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007793 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
Jordan Rose0e5badd2012-12-05 18:44:49 +00007794 Sema::LookupOrdinaryName);
7795 if (S.LookupName(Result, S.getCurScope())) {
7796 NamedDecl *ND = Result.getFoundDecl();
7797 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7798 if (TD->getUnderlyingType() == IntendedTy)
7799 IntendedTy = S.Context.getTypedefType(TD);
7800 }
7801 }
7802 }
7803
7804 // Special-case some of Darwin's platform-independence types by suggesting
7805 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007806 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00007807 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007808 QualType CastTy;
7809 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7810 if (!CastTy.isNull()) {
Alex Lorenzb2043ac2018-07-05 22:51:11 +00007811 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
JF Bastienec7d7f32018-06-22 21:54:40 +00007812 // (long in ASTContext). Only complain to pedants.
7813 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
Alex Lorenzb2043ac2018-07-05 22:51:11 +00007814 (AT.isSizeT() || AT.isPtrdiffT()) &&
7815 AT.matchesType(S.Context, CastTy))
JF Bastienec7d7f32018-06-22 21:54:40 +00007816 Pedantic = true;
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007817 IntendedTy = CastTy;
7818 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00007819 }
7820 }
7821
Jordan Rose22b74712012-09-05 22:56:19 +00007822 // We may be able to offer a FixItHint if it is a supported type.
7823 PrintfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00007824 bool Success =
Mehdi Amini06d367c2016-10-24 20:39:34 +00007825 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007826
JF Bastienec7d7f32018-06-22 21:54:40 +00007827 if (Success) {
Jordan Rose22b74712012-09-05 22:56:19 +00007828 // Get the fix string from the fixed format specifier
7829 SmallString<16> buf;
7830 llvm::raw_svector_ostream os(buf);
7831 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007832
Jordan Roseaee34382012-09-05 22:56:26 +00007833 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7834
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007835 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
JF Bastienec7d7f32018-06-22 21:54:40 +00007836 unsigned Diag =
7837 Pedantic
7838 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7839 : diag::warn_format_conversion_argument_type_mismatch;
Jordan Rose0e5badd2012-12-05 18:44:49 +00007840 // In this case, the specifier is wrong and should be changed to match
7841 // the argument.
JF Bastienec7d7f32018-06-22 21:54:40 +00007842 EmitFormatDiagnostic(S.PDiag(Diag)
Daniel Jasperad8d8492015-03-04 14:18:20 +00007843 << AT.getRepresentativeTypeName(S.Context)
7844 << IntendedTy << IsEnum << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007845 E->getBeginLoc(),
Daniel Jasperad8d8492015-03-04 14:18:20 +00007846 /*IsStringLocation*/ false, SpecRange,
7847 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00007848 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00007849 // The canonical type for formatting this value is different from the
7850 // actual type of the expression. (This occurs, for example, with Darwin's
7851 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7852 // should be printed as 'long' for 64-bit compatibility.)
7853 // Rather than emitting a normal format/argument mismatch, we want to
7854 // add a cast to the recommended type (and correct the format string
7855 // if necessary).
7856 SmallString<16> CastBuf;
7857 llvm::raw_svector_ostream CastFix(CastBuf);
7858 CastFix << "(";
7859 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7860 CastFix << ")";
7861
7862 SmallVector<FixItHint,4> Hints;
Fangrui Song6907ce22018-07-30 19:24:48 +00007863 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00007864 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7865
7866 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7867 // If there's already a cast present, just replace it.
7868 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7869 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7870
7871 } else if (!requiresParensToAddCast(E)) {
7872 // If the expression has high enough precedence,
7873 // just write the C-style cast.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007874 Hints.push_back(
7875 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00007876 } else {
7877 // Otherwise, add parens around the expression as well as the cast.
7878 CastFix << "(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007879 Hints.push_back(
7880 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00007881
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007882 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
Jordan Roseaee34382012-09-05 22:56:26 +00007883 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7884 }
7885
Jordan Rose0e5badd2012-12-05 18:44:49 +00007886 if (ShouldNotPrintDirectly) {
7887 // The expression has a type that should not be printed directly.
7888 // We extract the name from the typedef because we don't want to show
7889 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007890 StringRef Name;
7891 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
7892 Name = TypedefTy->getDecl()->getName();
7893 else
7894 Name = CastTyName;
JF Bastienec7d7f32018-06-22 21:54:40 +00007895 unsigned Diag = Pedantic
7896 ? diag::warn_format_argument_needs_cast_pedantic
7897 : diag::warn_format_argument_needs_cast;
7898 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7899 << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007900 E->getBeginLoc(), /*IsStringLocation=*/false,
Jordan Rose0e5badd2012-12-05 18:44:49 +00007901 SpecRange, Hints);
7902 } else {
7903 // In this case, the expression could be printed using a different
Fangrui Song6907ce22018-07-30 19:24:48 +00007904 // specifier, but we've decided that the specifier is probably correct
Jordan Rose0e5badd2012-12-05 18:44:49 +00007905 // and we should cast instead. Just use the normal warning message.
7906 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007907 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7908 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
7909 << E->getSourceRange(),
7910 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
Jordan Rose0e5badd2012-12-05 18:44:49 +00007911 }
Jordan Roseaee34382012-09-05 22:56:26 +00007912 }
Jordan Rose22b74712012-09-05 22:56:19 +00007913 } else {
7914 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7915 SpecifierLen);
7916 // Since the warning for passing non-POD types to variadic functions
7917 // was deferred until now, we emit a warning for non-POD
7918 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00007919 switch (S.isValidVarArgType(ExprTy)) {
7920 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00007921 case Sema::VAK_ValidInCXX11: {
JF Bastienec7d7f32018-06-22 21:54:40 +00007922 unsigned Diag =
7923 Pedantic
7924 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7925 : diag::warn_format_conversion_argument_type_mismatch;
Richard Smithd7293d72013-08-05 18:49:43 +00007926
Seth Cantrellb4802962015-03-04 03:12:10 +00007927 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00007928 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
Seth Cantrellb4802962015-03-04 03:12:10 +00007929 << IsEnum << CSR << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007930 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Seth Cantrellb4802962015-03-04 03:12:10 +00007931 break;
7932 }
Richard Smithd7293d72013-08-05 18:49:43 +00007933 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00007934 case Sema::VAK_MSVCUndefined:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007935 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7936 << S.getLangOpts().CPlusPlus11 << ExprTy
7937 << CallType
7938 << AT.getRepresentativeTypeName(S.Context) << CSR
7939 << E->getSourceRange(),
7940 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00007941 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00007942 break;
7943
7944 case Sema::VAK_Invalid:
7945 if (ExprTy->isObjCObjectType())
7946 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007947 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7948 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7949 << AT.getRepresentativeTypeName(S.Context) << CSR
7950 << E->getSourceRange(),
7951 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00007952 else
7953 // FIXME: If this is an initializer list, suggest removing the braces
7954 // or inserting a cast to the target type.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007955 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
7956 << isa<InitListExpr>(E) << ExprTy << CallType
7957 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
Richard Smithd7293d72013-08-05 18:49:43 +00007958 break;
7959 }
7960
7961 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7962 "format string specifier index out of range");
7963 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007964 }
7965
Ted Kremenekab278de2010-01-28 23:39:18 +00007966 return true;
7967}
7968
Ted Kremenek02087932010-07-16 02:11:22 +00007969//===--- CHECK: Scanf format string checking ------------------------------===//
7970
Fangrui Song6907ce22018-07-30 19:24:48 +00007971namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007972
Ted Kremenek02087932010-07-16 02:11:22 +00007973class CheckScanfHandler : public CheckFormatHandler {
7974public:
Stephen Hines648c3692016-09-16 01:07:04 +00007975 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007976 const Expr *origFormatExpr, Sema::FormatStringType type,
7977 unsigned firstDataArg, unsigned numDataArgs,
7978 const char *beg, bool hasVAListArg,
7979 ArrayRef<const Expr *> Args, unsigned formatIdx,
7980 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007981 llvm::SmallBitVector &CheckedVarArgs,
7982 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007983 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7984 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7985 inFunctionCall, CallType, CheckedVarArgs,
7986 UncoveredArg) {}
7987
Ted Kremenek02087932010-07-16 02:11:22 +00007988 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7989 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007990 unsigned specifierLen) override;
Fangrui Song6907ce22018-07-30 19:24:48 +00007991
Ted Kremenekce815422010-07-19 21:25:57 +00007992 bool HandleInvalidScanfConversionSpecifier(
7993 const analyze_scanf::ScanfSpecifier &FS,
7994 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007995 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007996
Craig Toppere14c0f82014-03-12 04:55:44 +00007997 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00007998};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007999
8000} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00008001
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008002void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8003 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008004 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8005 getLocationOfByte(end), /*IsStringLocation*/true,
8006 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008007}
8008
Ted Kremenekce815422010-07-19 21:25:57 +00008009bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8010 const analyze_scanf::ScanfSpecifier &FS,
8011 const char *startSpecifier,
8012 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008013 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00008014 FS.getConversionSpecifier();
8015
8016 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8017 getLocationOfByte(CS.getStart()),
8018 startSpecifier, specifierLen,
8019 CS.getStart(), CS.getLength());
8020}
8021
Ted Kremenek02087932010-07-16 02:11:22 +00008022bool CheckScanfHandler::HandleScanfSpecifier(
8023 const analyze_scanf::ScanfSpecifier &FS,
8024 const char *startSpecifier,
8025 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00008026 using namespace analyze_scanf;
Fangrui Song6907ce22018-07-30 19:24:48 +00008027 using namespace analyze_format_string;
Ted Kremenek02087932010-07-16 02:11:22 +00008028
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008029 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00008030
Ted Kremenek6cd69422010-07-19 22:01:06 +00008031 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8032 // be used to decide if we are using positional arguments consistently.
8033 if (FS.consumesDataArgument()) {
8034 if (atFirstArg) {
8035 atFirstArg = false;
8036 usesPositionalArgs = FS.usesPositionalArg();
8037 }
8038 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008039 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8040 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00008041 return false;
8042 }
Ted Kremenek02087932010-07-16 02:11:22 +00008043 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008044
Ted Kremenek02087932010-07-16 02:11:22 +00008045 // Check if the field with is non-zero.
8046 const OptionalAmount &Amt = FS.getFieldWidth();
8047 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8048 if (Amt.getConstantAmount() == 0) {
8049 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8050 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00008051 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8052 getLocationOfByte(Amt.getStart()),
8053 /*IsStringLocation*/true, R,
8054 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00008055 }
8056 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008057
Ted Kremenek02087932010-07-16 02:11:22 +00008058 if (!FS.consumesDataArgument()) {
8059 // FIXME: Technically specifying a precision or field width here
8060 // makes no sense. Worth issuing a warning at some point.
8061 return true;
8062 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008063
Ted Kremenek02087932010-07-16 02:11:22 +00008064 // Consume the argument.
8065 unsigned argIndex = FS.getArgIndex();
8066 if (argIndex < NumDataArgs) {
8067 // The check to see if the argIndex is valid will come later.
8068 // We set the bit here because we may exit early from this
8069 // function if we encounter some other error.
8070 CoveredArgs.set(argIndex);
8071 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008072
Ted Kremenek4407ea42010-07-20 20:04:47 +00008073 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00008074 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00008075 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8076 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00008077 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008078 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00008079 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008080 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8081 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00008082
Jordan Rose92303592012-09-08 04:00:03 +00008083 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8084 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8085
Ted Kremenek02087932010-07-16 02:11:22 +00008086 // The remaining checks depend on the data arguments.
8087 if (HasVAListArg)
8088 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008089
Ted Kremenek6adb7e32010-07-26 19:45:42 +00008090 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00008091 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00008092
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008093 // Check that the argument type matches the format specifier.
8094 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00008095 if (!Ex)
8096 return true;
8097
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00008098 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00008099
8100 if (!AT.isValid()) {
8101 return true;
8102 }
8103
JF Bastienec7d7f32018-06-22 21:54:40 +00008104 analyze_format_string::ArgType::MatchKind Match =
Seth Cantrellb4802962015-03-04 03:12:10 +00008105 AT.matchesType(S.Context, Ex->getType());
JF Bastienec7d7f32018-06-22 21:54:40 +00008106 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8107 if (Match == analyze_format_string::ArgType::Match)
Seth Cantrell79340072015-03-04 05:58:08 +00008108 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008109
Seth Cantrell79340072015-03-04 05:58:08 +00008110 ScanfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00008111 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
Seth Cantrell79340072015-03-04 05:58:08 +00008112 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008113
JF Bastienec7d7f32018-06-22 21:54:40 +00008114 unsigned Diag =
8115 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8116 : diag::warn_format_conversion_argument_type_mismatch;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008117
JF Bastienec7d7f32018-06-22 21:54:40 +00008118 if (Success) {
Seth Cantrell79340072015-03-04 05:58:08 +00008119 // Get the fix string from the fixed format specifier.
8120 SmallString<128> buf;
8121 llvm::raw_svector_ostream os(buf);
8122 fixedFS.toString(os);
8123
8124 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008125 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
Seth Cantrell79340072015-03-04 05:58:08 +00008126 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008127 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008128 /*IsStringLocation*/ false,
8129 getSpecifierRange(startSpecifier, specifierLen),
8130 FixItHint::CreateReplacement(
8131 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8132 } else {
JF Bastienec7d7f32018-06-22 21:54:40 +00008133 EmitFormatDiagnostic(S.PDiag(Diag)
Seth Cantrell79340072015-03-04 05:58:08 +00008134 << AT.getRepresentativeTypeName(S.Context)
8135 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008136 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008137 /*IsStringLocation*/ false,
8138 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008139 }
8140
Ted Kremenek02087932010-07-16 02:11:22 +00008141 return true;
8142}
8143
Stephen Hines648c3692016-09-16 01:07:04 +00008144static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008145 const Expr *OrigFormatExpr,
8146 ArrayRef<const Expr *> Args,
8147 bool HasVAListArg, unsigned format_idx,
8148 unsigned firstDataArg,
8149 Sema::FormatStringType Type,
8150 bool inFunctionCall,
8151 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008152 llvm::SmallBitVector &CheckedVarArgs,
8153 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00008154 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00008155 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008156 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008157 S, inFunctionCall, Args[format_idx],
8158 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8159 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008160 return;
8161 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008162
Ted Kremenekab278de2010-01-28 23:39:18 +00008163 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008164 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00008165 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008166 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008167 const ConstantArrayType *T =
8168 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008169 assert(T && "String literal not of constant array type!");
8170 size_t TypeSize = T->getSize().getZExtValue();
8171 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00008172 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008173
8174 // Emit a warning if the string literal is truncated and does not contain an
8175 // embedded null character.
8176 if (TypeSize <= StrRef.size() &&
8177 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8178 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008179 S, inFunctionCall, Args[format_idx],
8180 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008181 FExpr->getBeginLoc(),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008182 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8183 return;
8184 }
8185
Ted Kremenekab278de2010-01-28 23:39:18 +00008186 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00008187 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008188 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008189 S, inFunctionCall, Args[format_idx],
8190 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8191 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008192 return;
8193 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008194
8195 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00008196 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8197 Type == Sema::FST_OSTrace) {
8198 CheckPrintfHandler H(
8199 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8200 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8201 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8202 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008203
Hans Wennborg23926bd2011-12-15 10:25:47 +00008204 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008205 S.getLangOpts(),
8206 S.Context.getTargetInfo(),
8207 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00008208 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008209 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00008210 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8211 numDataArgs, Str, HasVAListArg, Args, format_idx,
8212 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008213
Hans Wennborg23926bd2011-12-15 10:25:47 +00008214 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008215 S.getLangOpts(),
8216 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00008217 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00008218 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00008219}
8220
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00008221bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8222 // Str - The format string. NOTE: this is NOT null-terminated!
8223 StringRef StrRef = FExpr->getString();
8224 const char *Str = StrRef.data();
8225 // Account for cases where the string literal is truncated in a declaration.
8226 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8227 assert(T && "String literal not of constant array type!");
8228 size_t TypeSize = T->getSize().getZExtValue();
8229 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8230 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8231 getLangOpts(),
8232 Context.getTargetInfo());
8233}
8234
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008235//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8236
8237// Returns the related absolute value function that is larger, of 0 if one
8238// does not exist.
8239static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8240 switch (AbsFunction) {
8241 default:
8242 return 0;
8243
8244 case Builtin::BI__builtin_abs:
8245 return Builtin::BI__builtin_labs;
8246 case Builtin::BI__builtin_labs:
8247 return Builtin::BI__builtin_llabs;
8248 case Builtin::BI__builtin_llabs:
8249 return 0;
8250
8251 case Builtin::BI__builtin_fabsf:
8252 return Builtin::BI__builtin_fabs;
8253 case Builtin::BI__builtin_fabs:
8254 return Builtin::BI__builtin_fabsl;
8255 case Builtin::BI__builtin_fabsl:
8256 return 0;
8257
8258 case Builtin::BI__builtin_cabsf:
8259 return Builtin::BI__builtin_cabs;
8260 case Builtin::BI__builtin_cabs:
8261 return Builtin::BI__builtin_cabsl;
8262 case Builtin::BI__builtin_cabsl:
8263 return 0;
8264
8265 case Builtin::BIabs:
8266 return Builtin::BIlabs;
8267 case Builtin::BIlabs:
8268 return Builtin::BIllabs;
8269 case Builtin::BIllabs:
8270 return 0;
8271
8272 case Builtin::BIfabsf:
8273 return Builtin::BIfabs;
8274 case Builtin::BIfabs:
8275 return Builtin::BIfabsl;
8276 case Builtin::BIfabsl:
8277 return 0;
8278
8279 case Builtin::BIcabsf:
8280 return Builtin::BIcabs;
8281 case Builtin::BIcabs:
8282 return Builtin::BIcabsl;
8283 case Builtin::BIcabsl:
8284 return 0;
8285 }
8286}
8287
8288// Returns the argument type of the absolute value function.
8289static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8290 unsigned AbsType) {
8291 if (AbsType == 0)
8292 return QualType();
8293
8294 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8295 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8296 if (Error != ASTContext::GE_None)
8297 return QualType();
8298
8299 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8300 if (!FT)
8301 return QualType();
8302
8303 if (FT->getNumParams() != 1)
8304 return QualType();
8305
8306 return FT->getParamType(0);
8307}
8308
8309// Returns the best absolute value function, or zero, based on type and
8310// current absolute value function.
8311static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8312 unsigned AbsFunctionKind) {
8313 unsigned BestKind = 0;
8314 uint64_t ArgSize = Context.getTypeSize(ArgType);
8315 for (unsigned Kind = AbsFunctionKind; Kind != 0;
8316 Kind = getLargerAbsoluteValueFunction(Kind)) {
8317 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8318 if (Context.getTypeSize(ParamType) >= ArgSize) {
8319 if (BestKind == 0)
8320 BestKind = Kind;
8321 else if (Context.hasSameType(ParamType, ArgType)) {
8322 BestKind = Kind;
8323 break;
8324 }
8325 }
8326 }
8327 return BestKind;
8328}
8329
8330enum AbsoluteValueKind {
8331 AVK_Integer,
8332 AVK_Floating,
8333 AVK_Complex
8334};
8335
8336static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8337 if (T->isIntegralOrEnumerationType())
8338 return AVK_Integer;
8339 if (T->isRealFloatingType())
8340 return AVK_Floating;
8341 if (T->isAnyComplexType())
8342 return AVK_Complex;
8343
8344 llvm_unreachable("Type not integer, floating, or complex");
8345}
8346
8347// Changes the absolute value function to a different type. Preserves whether
8348// the function is a builtin.
8349static unsigned changeAbsFunction(unsigned AbsKind,
8350 AbsoluteValueKind ValueKind) {
8351 switch (ValueKind) {
8352 case AVK_Integer:
8353 switch (AbsKind) {
8354 default:
8355 return 0;
8356 case Builtin::BI__builtin_fabsf:
8357 case Builtin::BI__builtin_fabs:
8358 case Builtin::BI__builtin_fabsl:
8359 case Builtin::BI__builtin_cabsf:
8360 case Builtin::BI__builtin_cabs:
8361 case Builtin::BI__builtin_cabsl:
8362 return Builtin::BI__builtin_abs;
8363 case Builtin::BIfabsf:
8364 case Builtin::BIfabs:
8365 case Builtin::BIfabsl:
8366 case Builtin::BIcabsf:
8367 case Builtin::BIcabs:
8368 case Builtin::BIcabsl:
8369 return Builtin::BIabs;
8370 }
8371 case AVK_Floating:
8372 switch (AbsKind) {
8373 default:
8374 return 0;
8375 case Builtin::BI__builtin_abs:
8376 case Builtin::BI__builtin_labs:
8377 case Builtin::BI__builtin_llabs:
8378 case Builtin::BI__builtin_cabsf:
8379 case Builtin::BI__builtin_cabs:
8380 case Builtin::BI__builtin_cabsl:
8381 return Builtin::BI__builtin_fabsf;
8382 case Builtin::BIabs:
8383 case Builtin::BIlabs:
8384 case Builtin::BIllabs:
8385 case Builtin::BIcabsf:
8386 case Builtin::BIcabs:
8387 case Builtin::BIcabsl:
8388 return Builtin::BIfabsf;
8389 }
8390 case AVK_Complex:
8391 switch (AbsKind) {
8392 default:
8393 return 0;
8394 case Builtin::BI__builtin_abs:
8395 case Builtin::BI__builtin_labs:
8396 case Builtin::BI__builtin_llabs:
8397 case Builtin::BI__builtin_fabsf:
8398 case Builtin::BI__builtin_fabs:
8399 case Builtin::BI__builtin_fabsl:
8400 return Builtin::BI__builtin_cabsf;
8401 case Builtin::BIabs:
8402 case Builtin::BIlabs:
8403 case Builtin::BIllabs:
8404 case Builtin::BIfabsf:
8405 case Builtin::BIfabs:
8406 case Builtin::BIfabsl:
8407 return Builtin::BIcabsf;
8408 }
8409 }
8410 llvm_unreachable("Unable to convert function");
8411}
8412
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00008413static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008414 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8415 if (!FnInfo)
8416 return 0;
8417
8418 switch (FDecl->getBuiltinID()) {
8419 default:
8420 return 0;
8421 case Builtin::BI__builtin_abs:
8422 case Builtin::BI__builtin_fabs:
8423 case Builtin::BI__builtin_fabsf:
8424 case Builtin::BI__builtin_fabsl:
8425 case Builtin::BI__builtin_labs:
8426 case Builtin::BI__builtin_llabs:
8427 case Builtin::BI__builtin_cabs:
8428 case Builtin::BI__builtin_cabsf:
8429 case Builtin::BI__builtin_cabsl:
8430 case Builtin::BIabs:
8431 case Builtin::BIlabs:
8432 case Builtin::BIllabs:
8433 case Builtin::BIfabs:
8434 case Builtin::BIfabsf:
8435 case Builtin::BIfabsl:
8436 case Builtin::BIcabs:
8437 case Builtin::BIcabsf:
8438 case Builtin::BIcabsl:
8439 return FDecl->getBuiltinID();
8440 }
8441 llvm_unreachable("Unknown Builtin type");
8442}
8443
8444// If the replacement is valid, emit a note with replacement function.
8445// Additionally, suggest including the proper header if not already included.
8446static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00008447 unsigned AbsKind, QualType ArgType) {
8448 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00008449 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00008450 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008451 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8452 FunctionName = "std::abs";
8453 if (ArgType->isIntegralOrEnumerationType()) {
8454 HeaderName = "cstdlib";
8455 } else if (ArgType->isRealFloatingType()) {
8456 HeaderName = "cmath";
8457 } else {
8458 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008459 }
Richard Trieubeffb832014-04-15 23:47:53 +00008460
8461 // Lookup all std::abs
8462 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00008463 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00008464 R.suppressDiagnostics();
8465 S.LookupQualifiedName(R, Std);
8466
8467 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008468 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008469 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8470 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8471 } else {
8472 FDecl = dyn_cast<FunctionDecl>(I);
8473 }
8474 if (!FDecl)
8475 continue;
8476
8477 // Found std::abs(), check that they are the right ones.
8478 if (FDecl->getNumParams() != 1)
8479 continue;
8480
8481 // Check that the parameter type can handle the argument.
8482 QualType ParamType = FDecl->getParamDecl(0)->getType();
8483 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8484 S.Context.getTypeSize(ArgType) <=
8485 S.Context.getTypeSize(ParamType)) {
8486 // Found a function, don't need the header hint.
8487 EmitHeaderHint = false;
8488 break;
8489 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008490 }
Richard Trieubeffb832014-04-15 23:47:53 +00008491 }
8492 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00008493 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00008494 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8495
8496 if (HeaderName) {
8497 DeclarationName DN(&S.Context.Idents.get(FunctionName));
8498 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8499 R.suppressDiagnostics();
8500 S.LookupName(R, S.getCurScope());
8501
8502 if (R.isSingleResult()) {
8503 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8504 if (FD && FD->getBuiltinID() == AbsKind) {
8505 EmitHeaderHint = false;
8506 } else {
8507 return;
8508 }
8509 } else if (!R.empty()) {
8510 return;
8511 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008512 }
8513 }
8514
8515 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00008516 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008517
Richard Trieubeffb832014-04-15 23:47:53 +00008518 if (!HeaderName)
8519 return;
8520
8521 if (!EmitHeaderHint)
8522 return;
8523
Alp Toker5d96e0a2014-07-11 20:53:51 +00008524 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8525 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00008526}
8527
Richard Trieua7f30b12016-12-06 01:42:28 +00008528template <std::size_t StrLen>
8529static bool IsStdFunction(const FunctionDecl *FDecl,
8530 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00008531 if (!FDecl)
8532 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008533 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00008534 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008535 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00008536 return false;
8537
8538 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008539}
8540
8541// Warn when using the wrong abs() function.
8542void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00008543 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008544 if (Call->getNumArgs() != 1)
8545 return;
8546
8547 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00008548 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00008549 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008550 return;
8551
8552 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8553 QualType ParamType = Call->getArg(0)->getType();
8554
Alp Toker5d96e0a2014-07-11 20:53:51 +00008555 // Unsigned types cannot be negative. Suggest removing the absolute value
8556 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008557 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00008558 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00008559 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008560 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8561 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00008562 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008563 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8564 return;
8565 }
8566
David Majnemer7f77eb92015-11-15 03:04:34 +00008567 // Taking the absolute value of a pointer is very suspicious, they probably
8568 // wanted to index into an array, dereference a pointer, call a function, etc.
8569 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8570 unsigned DiagType = 0;
8571 if (ArgType->isFunctionType())
8572 DiagType = 1;
8573 else if (ArgType->isArrayType())
8574 DiagType = 2;
8575
8576 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8577 return;
8578 }
8579
Richard Trieubeffb832014-04-15 23:47:53 +00008580 // std::abs has overloads which prevent most of the absolute value problems
8581 // from occurring.
8582 if (IsStdAbs)
8583 return;
8584
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008585 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8586 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8587
8588 // The argument and parameter are the same kind. Check if they are the right
8589 // size.
8590 if (ArgValueKind == ParamValueKind) {
8591 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8592 return;
8593
8594 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8595 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8596 << FDecl << ArgType << ParamType;
8597
8598 if (NewAbsKind == 0)
8599 return;
8600
8601 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00008602 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008603 return;
8604 }
8605
8606 // ArgValueKind != ParamValueKind
8607 // The wrong type of absolute value function was used. Attempt to find the
8608 // proper one.
8609 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8610 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8611 if (NewAbsKind == 0)
8612 return;
8613
8614 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8615 << FDecl << ParamValueKind << ArgValueKind;
8616
8617 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00008618 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008619}
8620
Richard Trieu67c00712016-12-05 23:41:46 +00008621//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00008622void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8623 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00008624 if (!Call || !FDecl) return;
8625
8626 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008627 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00008628 if (Call->getExprLoc().isMacroID()) return;
8629
8630 // Only care about the one template argument, two function parameter std::max
8631 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00008632 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00008633 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8634 if (!ArgList) return;
8635 if (ArgList->size() != 1) return;
8636
8637 // Check that template type argument is unsigned integer.
8638 const auto& TA = ArgList->get(0);
8639 if (TA.getKind() != TemplateArgument::Type) return;
8640 QualType ArgType = TA.getAsType();
8641 if (!ArgType->isUnsignedIntegerType()) return;
8642
8643 // See if either argument is a literal zero.
8644 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8645 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8646 if (!MTE) return false;
8647 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8648 if (!Num) return false;
8649 if (Num->getValue() != 0) return false;
8650 return true;
8651 };
8652
8653 const Expr *FirstArg = Call->getArg(0);
8654 const Expr *SecondArg = Call->getArg(1);
8655 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8656 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8657
8658 // Only warn when exactly one argument is zero.
8659 if (IsFirstArgZero == IsSecondArgZero) return;
8660
8661 SourceRange FirstRange = FirstArg->getSourceRange();
8662 SourceRange SecondRange = SecondArg->getSourceRange();
8663
8664 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8665
8666 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8667 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8668
8669 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8670 SourceRange RemovalRange;
8671 if (IsFirstArgZero) {
8672 RemovalRange = SourceRange(FirstRange.getBegin(),
8673 SecondRange.getBegin().getLocWithOffset(-1));
8674 } else {
8675 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8676 SecondRange.getEnd());
8677 }
8678
8679 Diag(Call->getExprLoc(), diag::note_remove_max_call)
8680 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8681 << FixItHint::CreateRemoval(RemovalRange);
8682}
8683
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008684//===--- CHECK: Standard memory functions ---------------------------------===//
8685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008686/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00008687/// such as memcmp, strncat, etc and warns if it's a comparison.
8688///
8689/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8690static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8691 IdentifierInfo *FnName,
8692 SourceLocation FnLoc,
8693 SourceLocation RParenLoc) {
8694 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8695 if (!Size)
8696 return false;
8697
Richard Smithc70f1d62017-12-14 15:16:18 +00008698 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8699 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00008700 return false;
8701
Nico Weber0e6daef2013-12-26 23:38:39 +00008702 SourceRange SizeRange = Size->getSourceRange();
8703 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8704 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00008705 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008706 << FnName
8707 << FixItHint::CreateInsertion(
8708 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00008709 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00008710 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00008711 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00008712 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8713 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00008714
8715 return true;
8716}
8717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008718/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00008719/// (e.g., whether it has a vtable).
8720static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8721 bool &IsContained) {
8722 // Look through array types while ignoring qualifiers.
8723 const Type *Ty = T->getBaseElementTypeUnsafe();
8724 IsContained = false;
8725
8726 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8727 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00008728 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00008729 return nullptr;
8730
8731 if (RD->isDynamicClass())
8732 return RD;
8733
8734 // Check all the fields. If any bases were dynamic, the class is dynamic.
8735 // It's impossible for a class to transitively contain itself by value, so
8736 // infinite recursion is impossible.
8737 for (auto *FD : RD->fields()) {
8738 bool SubContained;
8739 if (const CXXRecordDecl *ContainedRD =
8740 getContainedDynamicClass(FD->getType(), SubContained)) {
8741 IsContained = true;
8742 return ContainedRD;
8743 }
8744 }
8745
8746 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00008747}
8748
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008749static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8750 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8751 if (Unary->getKind() == UETT_SizeOf)
8752 return Unary;
8753 return nullptr;
8754}
8755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008756/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008757/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00008758static const Expr *getSizeOfExprArg(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008759 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8760 if (!SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008761 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Craig Topperc3ec1492014-05-26 06:22:03 +00008762 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008763}
8764
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008765/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00008766static QualType getSizeOfArgType(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008767 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8768 return SizeOf->getTypeOfArgument();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008769 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00008770}
8771
Akira Hatanaka2be04412018-04-17 19:13:41 +00008772namespace {
8773
8774struct SearchNonTrivialToInitializeField
8775 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8776 using Super =
8777 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8778
8779 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8780
8781 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8782 SourceLocation SL) {
8783 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8784 asDerived().visitArray(PDIK, AT, SL);
8785 return;
8786 }
8787
8788 Super::visitWithKind(PDIK, FT, SL);
8789 }
8790
8791 void visitARCStrong(QualType FT, SourceLocation SL) {
8792 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8793 }
8794 void visitARCWeak(QualType FT, SourceLocation SL) {
8795 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8796 }
8797 void visitStruct(QualType FT, SourceLocation SL) {
8798 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8799 visit(FD->getType(), FD->getLocation());
8800 }
8801 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8802 const ArrayType *AT, SourceLocation SL) {
8803 visit(getContext().getBaseElementType(AT), SL);
8804 }
8805 void visitTrivial(QualType FT, SourceLocation SL) {}
8806
8807 static void diag(QualType RT, const Expr *E, Sema &S) {
8808 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8809 }
8810
8811 ASTContext &getContext() { return S.getASTContext(); }
8812
8813 const Expr *E;
8814 Sema &S;
8815};
8816
8817struct SearchNonTrivialToCopyField
8818 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8819 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8820
8821 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8822
8823 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8824 SourceLocation SL) {
8825 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8826 asDerived().visitArray(PCK, AT, SL);
8827 return;
8828 }
8829
8830 Super::visitWithKind(PCK, FT, SL);
8831 }
8832
8833 void visitARCStrong(QualType FT, SourceLocation SL) {
8834 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8835 }
8836 void visitARCWeak(QualType FT, SourceLocation SL) {
8837 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8838 }
8839 void visitStruct(QualType FT, SourceLocation SL) {
8840 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8841 visit(FD->getType(), FD->getLocation());
8842 }
8843 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8844 SourceLocation SL) {
8845 visit(getContext().getBaseElementType(AT), SL);
8846 }
8847 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8848 SourceLocation SL) {}
8849 void visitTrivial(QualType FT, SourceLocation SL) {}
8850 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8851
8852 static void diag(QualType RT, const Expr *E, Sema &S) {
8853 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8854 }
8855
8856 ASTContext &getContext() { return S.getASTContext(); }
8857
8858 const Expr *E;
8859 Sema &S;
8860};
8861
8862}
8863
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008864/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8865static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8866 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8867
8868 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8869 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8870 return false;
8871
8872 return doesExprLikelyComputeSize(BO->getLHS()) ||
8873 doesExprLikelyComputeSize(BO->getRHS());
8874 }
8875
8876 return getAsSizeOfExpr(SizeofExpr) != nullptr;
8877}
8878
8879/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8880///
8881/// \code
8882/// #define MACRO 0
8883/// foo(MACRO);
8884/// foo(0);
8885/// \endcode
8886///
8887/// This should return true for the first call to foo, but not for the second
8888/// (regardless of whether foo is a macro or function).
8889static bool isArgumentExpandedFromMacro(SourceManager &SM,
8890 SourceLocation CallLoc,
8891 SourceLocation ArgLoc) {
8892 if (!CallLoc.isMacroID())
8893 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8894
8895 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8896 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8897}
8898
8899/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8900/// last two arguments transposed.
8901static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8902 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8903 return;
8904
8905 const Expr *SizeArg =
8906 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8907
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00008908 auto isLiteralZero = [](const Expr *E) {
8909 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
8910 };
8911
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008912 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8913 SourceLocation CallLoc = Call->getRParenLoc();
8914 SourceManager &SM = S.getSourceManager();
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00008915 if (isLiteralZero(SizeArg) &&
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008916 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
8917
8918 SourceLocation DiagLoc = SizeArg->getExprLoc();
8919
8920 // Some platforms #define bzero to __builtin_memset. See if this is the
8921 // case, and if so, emit a better diagnostic.
8922 if (BId == Builtin::BIbzero ||
8923 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
8924 CallLoc, SM, S.getLangOpts()) == "bzero")) {
8925 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
8926 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00008927 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008928 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
8929 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
8930 }
8931 return;
8932 }
8933
8934 // If the second argument to a memset is a sizeof expression and the third
8935 // isn't, this is also likely an error. This should catch
8936 // 'memset(buf, sizeof(buf), 0xff)'.
8937 if (BId == Builtin::BImemset &&
8938 doesExprLikelyComputeSize(Call->getArg(1)) &&
8939 !doesExprLikelyComputeSize(Call->getArg(2))) {
8940 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
8941 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
8942 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
8943 return;
8944 }
8945}
8946
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008947/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008948///
Chandler Carruthac687262011-06-03 06:23:57 +00008949/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00008950/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
8951/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008952///
8953/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00008954void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00008955 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00008956 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00008957 assert(BId != 0);
8958
Ted Kremenekb5fabb22011-04-28 01:38:02 +00008959 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00008960 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00008961 unsigned ExpectedNumArgs =
8962 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00008963 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00008964 return;
8965
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00008966 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00008967 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00008968 unsigned LenArg =
8969 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00008970 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008971
Nico Weber0e6daef2013-12-26 23:38:39 +00008972 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008973 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00008974 return;
8975
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008976 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
8977 CheckMemaccessSize(*this, BId, Call);
8978
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008979 // We have special checking when the length is a sizeof expression.
8980 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
8981 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
8982 llvm::FoldingSetNodeID SizeOfArgID;
8983
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00008984 // Although widely used, 'bzero' is not a standard function. Be more strict
8985 // with the argument types before allowing diagnostics and only allow the
8986 // form bzero(ptr, sizeof(...)).
8987 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8988 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
8989 return;
8990
Douglas Gregor3bb2a812011-05-03 20:37:33 +00008991 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
8992 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00008993 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008994
Douglas Gregor3bb2a812011-05-03 20:37:33 +00008995 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00008996 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00008997 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00008998 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00008999
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009000 // Never warn about void type pointers. This can be used to suppress
9001 // false positives.
9002 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009003 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009004
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009005 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9006 // actually comparing the expressions for equality. Because computing the
9007 // expression IDs can be expensive, we only do this if the diagnostic is
9008 // enabled.
9009 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009010 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9011 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009012 // We only compute IDs for expressions if the warning is enabled, and
9013 // cache the sizeof arg's ID.
9014 if (SizeOfArgID == llvm::FoldingSetNodeID())
9015 SizeOfArg->Profile(SizeOfArgID, Context, true);
9016 llvm::FoldingSetNodeID DestID;
9017 Dest->Profile(DestID, Context, true);
9018 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00009019 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9020 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009021 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00009022 StringRef ReadableName = FnName->getName();
9023
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009024 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00009025 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009026 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00009027 if (!PointeeTy->isIncompleteType() &&
9028 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009029 ActionIdx = 2; // If the pointee's size is sizeof(char),
9030 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00009031
9032 // If the function is defined as a builtin macro, do not show macro
9033 // expansion.
9034 SourceLocation SL = SizeOfArg->getExprLoc();
9035 SourceRange DSR = Dest->getSourceRange();
9036 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009037 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00009038
9039 if (SM.isMacroArgExpansion(SL)) {
9040 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9041 SL = SM.getSpellingLoc(SL);
9042 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9043 SM.getSpellingLoc(DSR.getEnd()));
9044 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9045 SM.getSpellingLoc(SSR.getEnd()));
9046 }
9047
Anna Zaksd08d9152012-05-30 23:14:52 +00009048 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009049 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00009050 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00009051 << PointeeTy
9052 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00009053 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00009054 << SSR);
9055 DiagRuntimeBehavior(SL, SizeOfArg,
9056 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9057 << ActionIdx
9058 << SSR);
9059
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009060 break;
9061 }
9062 }
9063
9064 // Also check for cases where the sizeof argument is the exact same
9065 // type as the memory argument, and where it points to a user-defined
9066 // record type.
9067 if (SizeOfArgTy != QualType()) {
9068 if (PointeeTy->isRecordType() &&
9069 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9070 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9071 PDiag(diag::warn_sizeof_pointer_type_memaccess)
9072 << FnName << SizeOfArgTy << ArgIdx
9073 << PointeeTy << Dest->getSourceRange()
9074 << LenExpr->getSourceRange());
9075 break;
9076 }
Nico Weberc5e73862011-06-14 16:14:58 +00009077 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00009078 } else if (DestTy->isArrayType()) {
9079 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00009080 }
Nico Weberc5e73862011-06-14 16:14:58 +00009081
Nico Weberc44b35e2015-03-21 17:37:46 +00009082 if (PointeeTy == QualType())
9083 continue;
Anna Zaks22122702012-01-17 00:37:07 +00009084
Nico Weberc44b35e2015-03-21 17:37:46 +00009085 // Always complain about dynamic classes.
9086 bool IsContained;
9087 if (const CXXRecordDecl *ContainedRD =
9088 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00009089
Nico Weberc44b35e2015-03-21 17:37:46 +00009090 unsigned OperationType = 0;
9091 // "overwritten" if we're warning about the destination for any call
9092 // but memcmp; otherwise a verb appropriate to the call.
9093 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
9094 if (BId == Builtin::BImemcpy)
9095 OperationType = 1;
9096 else if(BId == Builtin::BImemmove)
9097 OperationType = 2;
9098 else if (BId == Builtin::BImemcmp)
9099 OperationType = 3;
9100 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009101
John McCall31168b02011-06-15 23:02:42 +00009102 DiagRuntimeBehavior(
9103 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00009104 PDiag(diag::warn_dyn_class_memaccess)
9105 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
9106 << FnName << IsContained << ContainedRD << OperationType
9107 << Call->getCallee()->getSourceRange());
9108 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9109 BId != Builtin::BImemset)
9110 DiagRuntimeBehavior(
9111 Dest->getExprLoc(), Dest,
9112 PDiag(diag::warn_arc_object_memaccess)
9113 << ArgIdx << FnName << PointeeTy
9114 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00009115 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9116 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9117 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9118 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9119 PDiag(diag::warn_cstruct_memaccess)
9120 << ArgIdx << FnName << PointeeTy << 0);
9121 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9122 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9123 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9124 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9125 PDiag(diag::warn_cstruct_memaccess)
9126 << ArgIdx << FnName << PointeeTy << 1);
9127 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9128 } else {
9129 continue;
9130 }
9131 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00009132 continue;
9133
9134 DiagRuntimeBehavior(
9135 Dest->getExprLoc(), Dest,
9136 PDiag(diag::note_bad_memaccess_silence)
9137 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9138 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009139 }
9140}
9141
Ted Kremenek6865f772011-08-18 20:55:45 +00009142// A little helper routine: ignore addition and subtraction of integer literals.
9143// This intentionally does not ignore all integer constant expressions because
9144// we don't want to remove sizeof().
9145static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9146 Ex = Ex->IgnoreParenCasts();
9147
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009148 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00009149 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9150 if (!BO || !BO->isAdditiveOp())
9151 break;
9152
9153 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9154 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00009155
Ted Kremenek6865f772011-08-18 20:55:45 +00009156 if (isa<IntegerLiteral>(RHS))
9157 Ex = LHS;
9158 else if (isa<IntegerLiteral>(LHS))
9159 Ex = RHS;
9160 else
9161 break;
9162 }
9163
9164 return Ex;
9165}
9166
Anna Zaks13b08572012-08-08 21:42:23 +00009167static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9168 ASTContext &Context) {
9169 // Only handle constant-sized or VLAs, but not flexible members.
9170 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9171 // Only issue the FIXIT for arrays of size > 1.
9172 if (CAT->getSize().getSExtValue() <= 1)
9173 return false;
9174 } else if (!Ty->isVariableArrayType()) {
9175 return false;
9176 }
9177 return true;
9178}
9179
Ted Kremenek6865f772011-08-18 20:55:45 +00009180// Warn if the user has made the 'size' argument to strlcpy or strlcat
9181// be the size of the source, instead of the destination.
9182void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9183 IdentifierInfo *FnName) {
9184
9185 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00009186 unsigned NumArgs = Call->getNumArgs();
9187 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00009188 return;
9189
9190 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9191 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00009192 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00009193
9194 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009195 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009196 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009197
Ted Kremenek6865f772011-08-18 20:55:45 +00009198 // Look for 'strlcpy(dst, x, sizeof(x))'
9199 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9200 CompareWithSrc = Ex;
9201 else {
9202 // Look for 'strlcpy(dst, x, strlen(x))'
9203 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00009204 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9205 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00009206 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9207 }
9208 }
9209
9210 if (!CompareWithSrc)
9211 return;
9212
9213 // Determine if the argument to sizeof/strlen is equal to the source
9214 // argument. In principle there's all kinds of things you could do
9215 // here, for instance creating an == expression and evaluating it with
9216 // EvaluateAsBooleanCondition, but this uses a more direct technique:
9217 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9218 if (!SrcArgDRE)
9219 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009220
Ted Kremenek6865f772011-08-18 20:55:45 +00009221 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
Fangrui Song6907ce22018-07-30 19:24:48 +00009222 if (!CompareWithSrcDRE ||
Ted Kremenek6865f772011-08-18 20:55:45 +00009223 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9224 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009225
Ted Kremenek6865f772011-08-18 20:55:45 +00009226 const Expr *OriginalSizeArg = Call->getArg(2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009227 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9228 << OriginalSizeArg->getSourceRange() << FnName;
Fangrui Song6907ce22018-07-30 19:24:48 +00009229
Ted Kremenek6865f772011-08-18 20:55:45 +00009230 // Output a FIXIT hint if the destination is an array (rather than a
9231 // pointer to an array). This could be enhanced to handle some
9232 // pointers if we know the actual size, like if DstArg is 'array+2'
9233 // we could say 'sizeof(array)-2'.
9234 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00009235 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00009236 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009237
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009238 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009239 llvm::raw_svector_ostream OS(sizeString);
9240 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009241 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00009242 OS << ")";
Fangrui Song6907ce22018-07-30 19:24:48 +00009243
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009244 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9245 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9246 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00009247}
9248
Anna Zaks314cd092012-02-01 19:08:57 +00009249/// Check if two expressions refer to the same declaration.
9250static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9251 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9252 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9253 return D1->getDecl() == D2->getDecl();
9254 return false;
9255}
9256
9257static const Expr *getStrlenExprArg(const Expr *E) {
9258 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9259 const FunctionDecl *FD = CE->getDirectCallee();
9260 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00009261 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009262 return CE->getArg(0)->IgnoreParenCasts();
9263 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009264 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009265}
9266
9267// Warn on anti-patterns as the 'size' argument to strncat.
9268// The correct size argument should look like following:
9269// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9270void Sema::CheckStrncatArguments(const CallExpr *CE,
9271 IdentifierInfo *FnName) {
9272 // Don't crash if the user has the wrong number of arguments.
9273 if (CE->getNumArgs() < 3)
9274 return;
9275 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9276 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9277 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9278
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009279 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
Nico Weber0e6daef2013-12-26 23:38:39 +00009280 CE->getRParenLoc()))
9281 return;
9282
Anna Zaks314cd092012-02-01 19:08:57 +00009283 // Identify common expressions, which are wrongly used as the size argument
9284 // to strncat and may lead to buffer overflows.
9285 unsigned PatternType = 0;
9286 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9287 // - sizeof(dst)
9288 if (referToTheSameDecl(SizeOfArg, DstArg))
9289 PatternType = 1;
9290 // - sizeof(src)
9291 else if (referToTheSameDecl(SizeOfArg, SrcArg))
9292 PatternType = 2;
9293 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9294 if (BE->getOpcode() == BO_Sub) {
9295 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9296 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9297 // - sizeof(dst) - strlen(dst)
9298 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9299 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9300 PatternType = 1;
9301 // - sizeof(src) - (anything)
9302 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9303 PatternType = 2;
9304 }
9305 }
9306
9307 if (PatternType == 0)
9308 return;
9309
Anna Zaks5069aa32012-02-03 01:27:37 +00009310 // Generate the diagnostic.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009311 SourceLocation SL = LenArg->getBeginLoc();
Anna Zaks5069aa32012-02-03 01:27:37 +00009312 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009313 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00009314
9315 // If the function is defined as a builtin macro, do not show macro expansion.
9316 if (SM.isMacroArgExpansion(SL)) {
9317 SL = SM.getSpellingLoc(SL);
9318 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9319 SM.getSpellingLoc(SR.getEnd()));
9320 }
9321
Anna Zaks13b08572012-08-08 21:42:23 +00009322 // Check if the destination is an array (rather than a pointer to an array).
9323 QualType DstTy = DstArg->getType();
9324 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9325 Context);
9326 if (!isKnownSizeArray) {
9327 if (PatternType == 1)
9328 Diag(SL, diag::warn_strncat_wrong_size) << SR;
9329 else
9330 Diag(SL, diag::warn_strncat_src_size) << SR;
9331 return;
9332 }
9333
Anna Zaks314cd092012-02-01 19:08:57 +00009334 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00009335 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009336 else
Anna Zaks5069aa32012-02-03 01:27:37 +00009337 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009338
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009339 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00009340 llvm::raw_svector_ostream OS(sizeString);
9341 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009342 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009343 OS << ") - ";
9344 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009345 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009346 OS << ") - 1";
9347
Anna Zaks5069aa32012-02-03 01:27:37 +00009348 Diag(SL, diag::note_strncat_wrong_size)
9349 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00009350}
9351
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009352void
9353Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9354 SourceLocation ReturnLoc,
9355 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00009356 const AttrVec *Attrs,
9357 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009358 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00009359 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9360 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00009361 CheckNonNullExpr(*this, RetValExp))
9362 Diag(ReturnLoc, diag::warn_null_ret)
9363 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00009364
9365 // C++11 [basic.stc.dynamic.allocation]p4:
9366 // If an allocation function declared with a non-throwing
9367 // exception-specification fails to allocate storage, it shall return
9368 // a null pointer. Any other allocation function that fails to allocate
9369 // storage shall indicate failure only by throwing an exception [...]
9370 if (FD) {
9371 OverloadedOperatorKind Op = FD->getOverloadedOperator();
9372 if (Op == OO_New || Op == OO_Array_New) {
9373 const FunctionProtoType *Proto
9374 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00009375 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00009376 CheckNonNullExpr(*this, RetValExp))
9377 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9378 << FD << getLangOpts().CPlusPlus11;
9379 }
9380 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009381}
9382
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009383//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9384
9385/// Check for comparisons of floating point operands using != and ==.
9386/// Issue a warning if these are no self-comparisons, as they are not likely
9387/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00009388void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00009389 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9390 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009391
9392 // Special case: check for x == x (which is OK).
9393 // Do not emit warnings for such cases.
9394 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9395 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9396 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00009397 return;
Mike Stump11289f42009-09-09 15:08:12 +00009398
Ted Kremenekeda40e22007-11-29 00:59:04 +00009399 // Special case: check for comparisons against literals that can be exactly
9400 // represented by APFloat. In such cases, do not emit a warning. This
9401 // is a heuristic: often comparison against such literals are used to
9402 // detect if a value in a variable has not changed. This clearly can
9403 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00009404 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9405 if (FLL->isExact())
9406 return;
9407 } else
9408 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9409 if (FLR->isExact())
9410 return;
Mike Stump11289f42009-09-09 15:08:12 +00009411
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009412 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00009413 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009414 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009415 return;
Mike Stump11289f42009-09-09 15:08:12 +00009416
David Blaikie1f4ff152012-07-16 20:47:22 +00009417 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009418 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009419 return;
Mike Stump11289f42009-09-09 15:08:12 +00009420
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009421 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00009422 Diag(Loc, diag::warn_floatingpoint_eq)
9423 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009424}
John McCallca01b222010-01-04 23:21:16 +00009425
John McCall70aa5392010-01-06 05:24:50 +00009426//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9427//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00009428
John McCall70aa5392010-01-06 05:24:50 +00009429namespace {
John McCallca01b222010-01-04 23:21:16 +00009430
John McCall70aa5392010-01-06 05:24:50 +00009431/// Structure recording the 'active' range of an integer-valued
9432/// expression.
9433struct IntRange {
9434 /// The number of bits active in the int.
9435 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00009436
John McCall70aa5392010-01-06 05:24:50 +00009437 /// True if the int is known not to have negative values.
9438 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00009439
John McCall70aa5392010-01-06 05:24:50 +00009440 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009441 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00009442
John McCall817d4af2010-11-10 23:38:19 +00009443 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00009444 static IntRange forBoolType() {
9445 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00009446 }
9447
John McCall817d4af2010-11-10 23:38:19 +00009448 /// Returns the range of an opaque value of the given integral type.
9449 static IntRange forValueOfType(ASTContext &C, QualType T) {
9450 return forValueOfCanonicalType(C,
9451 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00009452 }
9453
John McCall817d4af2010-11-10 23:38:19 +00009454 /// Returns the range of an opaque value of a canonical integral type.
9455 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00009456 assert(T->isCanonicalUnqualified());
9457
9458 if (const VectorType *VT = dyn_cast<VectorType>(T))
9459 T = VT->getElementType().getTypePtr();
9460 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9461 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009462 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9463 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00009464
Roman Lebedevca1aaac2017-10-21 16:44:03 +00009465 if (!C.getLangOpts().CPlusPlus) {
9466 // For enum types in C code, use the underlying datatype.
9467 if (const EnumType *ET = dyn_cast<EnumType>(T))
9468 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9469 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9470 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00009471 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00009472 // In C++11, enums can have a fixed underlying type. Use this type to
9473 // compute the range.
9474 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00009475 return IntRange(C.getIntWidth(QualType(T, 0)),
9476 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00009477 }
John McCall18a2c2c2010-11-09 22:22:12 +00009478
David Majnemer6a426652013-06-07 22:07:20 +00009479 unsigned NumPositive = Enum->getNumPositiveBits();
9480 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00009481
David Majnemer6a426652013-06-07 22:07:20 +00009482 if (NumNegative == 0)
9483 return IntRange(NumPositive, true/*NonNegative*/);
9484 else
9485 return IntRange(std::max(NumPositive + 1, NumNegative),
9486 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00009487 }
John McCall70aa5392010-01-06 05:24:50 +00009488
9489 const BuiltinType *BT = cast<BuiltinType>(T);
9490 assert(BT->isInteger());
9491
9492 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9493 }
9494
John McCall817d4af2010-11-10 23:38:19 +00009495 /// Returns the "target" range of a canonical integral type, i.e.
9496 /// the range of values expressible in the type.
9497 ///
9498 /// This matches forValueOfCanonicalType except that enums have the
9499 /// full range of their type, not the range of their enumerators.
9500 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9501 assert(T->isCanonicalUnqualified());
9502
9503 if (const VectorType *VT = dyn_cast<VectorType>(T))
9504 T = VT->getElementType().getTypePtr();
9505 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9506 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009507 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9508 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009509 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00009510 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009511
9512 const BuiltinType *BT = cast<BuiltinType>(T);
9513 assert(BT->isInteger());
9514
9515 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9516 }
9517
9518 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00009519 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00009520 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00009521 L.NonNegative && R.NonNegative);
9522 }
9523
John McCall817d4af2010-11-10 23:38:19 +00009524 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00009525 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00009526 return IntRange(std::min(L.Width, R.Width),
9527 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00009528 }
9529};
9530
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009531} // namespace
9532
9533static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9534 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009535 if (value.isSigned() && value.isNegative())
9536 return IntRange(value.getMinSignedBits(), false);
9537
9538 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00009539 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009540
9541 // isNonNegative() just checks the sign bit without considering
9542 // signedness.
9543 return IntRange(value.getActiveBits(), true);
9544}
9545
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009546static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9547 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009548 if (result.isInt())
9549 return GetValueRange(C, result.getInt(), MaxWidth);
9550
9551 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00009552 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9553 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9554 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9555 R = IntRange::join(R, El);
9556 }
John McCall70aa5392010-01-06 05:24:50 +00009557 return R;
9558 }
9559
9560 if (result.isComplexInt()) {
9561 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9562 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9563 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00009564 }
9565
9566 // This can happen with lossless casts to intptr_t of "based" lvalues.
9567 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00009568 // FIXME: The only reason we need to pass the type in here is to get
9569 // the sign right on this one case. It would be nice if APValue
9570 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009571 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00009572 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00009573}
John McCall70aa5392010-01-06 05:24:50 +00009574
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009575static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009576 QualType Ty = E->getType();
9577 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9578 Ty = AtomicRHS->getValueType();
9579 return Ty;
9580}
9581
John McCall70aa5392010-01-06 05:24:50 +00009582/// Pseudo-evaluate the given integer expression, estimating the
9583/// range of values it might take.
9584///
9585/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009586static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009587 E = E->IgnoreParens();
9588
9589 // Try a full evaluation first.
9590 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009591 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00009592 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009593
9594 // I think we only want to look through implicit casts here; if the
9595 // user has an explicit widening cast, we should treat the value as
9596 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009597 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00009598 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00009599 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9600
Eli Friedmane6d33952013-07-08 20:20:06 +00009601 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00009602
George Burgess IVdf1ed002016-01-13 01:52:39 +00009603 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9604 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00009605
John McCall70aa5392010-01-06 05:24:50 +00009606 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00009607 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00009608 return OutputTypeRange;
9609
9610 IntRange SubRange
9611 = GetExprRange(C, CE->getSubExpr(),
9612 std::min(MaxWidth, OutputTypeRange.Width));
9613
9614 // Bail out if the subexpr's range is as wide as the cast type.
9615 if (SubRange.Width >= OutputTypeRange.Width)
9616 return OutputTypeRange;
9617
9618 // Otherwise, we take the smaller width, and we're non-negative if
9619 // either the output type or the subexpr is.
9620 return IntRange(SubRange.Width,
9621 SubRange.NonNegative || OutputTypeRange.NonNegative);
9622 }
9623
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009624 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009625 // If we can fold the condition, just take that operand.
9626 bool CondResult;
9627 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9628 return GetExprRange(C, CondResult ? CO->getTrueExpr()
9629 : CO->getFalseExpr(),
9630 MaxWidth);
9631
9632 // Otherwise, conservatively merge.
9633 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9634 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9635 return IntRange::join(L, R);
9636 }
9637
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009638 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009639 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00009640 case BO_Cmp:
9641 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00009642
9643 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00009644 case BO_LAnd:
9645 case BO_LOr:
9646 case BO_LT:
9647 case BO_GT:
9648 case BO_LE:
9649 case BO_GE:
9650 case BO_EQ:
9651 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009652 return IntRange::forBoolType();
9653
John McCallc3688382011-07-13 06:35:24 +00009654 // The type of the assignments is the type of the LHS, so the RHS
9655 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009656 case BO_MulAssign:
9657 case BO_DivAssign:
9658 case BO_RemAssign:
9659 case BO_AddAssign:
9660 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009661 case BO_XorAssign:
9662 case BO_OrAssign:
9663 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009664 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009665
John McCallc3688382011-07-13 06:35:24 +00009666 // Simple assignments just pass through the RHS, which will have
9667 // been coerced to the LHS type.
9668 case BO_Assign:
9669 // TODO: bitfields?
9670 return GetExprRange(C, BO->getRHS(), MaxWidth);
9671
John McCall70aa5392010-01-06 05:24:50 +00009672 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009673 case BO_PtrMemD:
9674 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009675 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009676
John McCall2ce81ad2010-01-06 22:07:33 +00009677 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009678 case BO_And:
9679 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009680 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9681 GetExprRange(C, BO->getRHS(), MaxWidth));
9682
John McCall70aa5392010-01-06 05:24:50 +00009683 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00009684 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00009685 // ...except that we want to treat '1 << (blah)' as logically
9686 // positive. It's an important idiom.
9687 if (IntegerLiteral *I
9688 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9689 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009690 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00009691 return IntRange(R.Width, /*NonNegative*/ true);
9692 }
9693 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009694 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00009695
John McCalle3027922010-08-25 11:45:40 +00009696 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00009697 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009698
John McCall2ce81ad2010-01-06 22:07:33 +00009699 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009700 case BO_Shr:
9701 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009702 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9703
9704 // If the shift amount is a positive constant, drop the width by
9705 // that much.
9706 llvm::APSInt shift;
9707 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9708 shift.isNonNegative()) {
9709 unsigned zext = shift.getZExtValue();
9710 if (zext >= L.Width)
9711 L.Width = (L.NonNegative ? 0 : 1);
9712 else
9713 L.Width -= zext;
9714 }
9715
9716 return L;
9717 }
9718
9719 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009720 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009721 return GetExprRange(C, BO->getRHS(), MaxWidth);
9722
John McCall2ce81ad2010-01-06 22:07:33 +00009723 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009724 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009725 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009726 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009727 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009728
John McCall51431812011-07-14 22:39:48 +00009729 // The width of a division result is mostly determined by the size
9730 // of the LHS.
9731 case BO_Div: {
9732 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009733 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009734 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9735
9736 // If the divisor is constant, use that.
9737 llvm::APSInt divisor;
9738 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9739 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9740 if (log2 >= L.Width)
9741 L.Width = (L.NonNegative ? 0 : 1);
9742 else
9743 L.Width = std::min(L.Width - log2, MaxWidth);
9744 return L;
9745 }
9746
9747 // Otherwise, just use the LHS's width.
9748 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9749 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9750 }
9751
9752 // The result of a remainder can't be larger than the result of
9753 // either side.
9754 case BO_Rem: {
9755 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009756 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009757 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9758 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9759
9760 IntRange meet = IntRange::meet(L, R);
9761 meet.Width = std::min(meet.Width, MaxWidth);
9762 return meet;
9763 }
9764
9765 // The default behavior is okay for these.
9766 case BO_Mul:
9767 case BO_Add:
9768 case BO_Xor:
9769 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009770 break;
9771 }
9772
John McCall51431812011-07-14 22:39:48 +00009773 // The default case is to treat the operation as if it were closed
9774 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009775 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9776 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9777 return IntRange::join(L, R);
9778 }
9779
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009780 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009781 switch (UO->getOpcode()) {
9782 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009783 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009784 return IntRange::forBoolType();
9785
9786 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009787 case UO_Deref:
9788 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009789 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009790
9791 default:
9792 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9793 }
9794 }
9795
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009796 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009797 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9798
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009799 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009800 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009801 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009802
Eli Friedmane6d33952013-07-08 20:20:06 +00009803 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009804}
John McCall263a48b2010-01-04 23:31:57 +00009805
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009806static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009807 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009808}
9809
John McCall263a48b2010-01-04 23:31:57 +00009810/// Checks whether the given value, which currently has the given
9811/// source semantics, has the same value when coerced through the
9812/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009813static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9814 const llvm::fltSemantics &Src,
9815 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009816 llvm::APFloat truncated = value;
9817
9818 bool ignored;
9819 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9820 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9821
9822 return truncated.bitwiseIsEqual(value);
9823}
9824
9825/// Checks whether the given value, which currently has the given
9826/// source semantics, has the same value when coerced through the
9827/// target semantics.
9828///
9829/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009830static bool IsSameFloatAfterCast(const APValue &value,
9831 const llvm::fltSemantics &Src,
9832 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009833 if (value.isFloat())
9834 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9835
9836 if (value.isVector()) {
9837 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9838 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9839 return false;
9840 return true;
9841 }
9842
9843 assert(value.isComplexFloat());
9844 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9845 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9846}
9847
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009848static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009849
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009850static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009851 // Suppress cases where we are comparing against an enum constant.
9852 if (const DeclRefExpr *DR =
9853 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9854 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009855 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009856
9857 // Suppress cases where the '0' value is expanded from a macro.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009858 if (E->getBeginLoc().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009859 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009860
Roman Lebedev6de129e2017-10-15 20:13:17 +00009861 return false;
9862}
9863
Richard Smith692f66ab2017-12-06 19:23:19 +00009864static bool isKnownToHaveUnsignedValue(Expr *E) {
9865 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009866 (!E->getType()->isSignedIntegerType() ||
9867 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9868}
9869
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009870namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009871/// The promoted range of values of a type. In general this has the
9872/// following structure:
9873///
9874/// |-----------| . . . |-----------|
9875/// ^ ^ ^ ^
9876/// Min HoleMin HoleMax Max
9877///
9878/// ... where there is only a hole if a signed type is promoted to unsigned
9879/// (in which case Min and Max are the smallest and largest representable
9880/// values).
9881struct PromotedRange {
9882 // Min, or HoleMax if there is a hole.
9883 llvm::APSInt PromotedMin;
9884 // Max, or HoleMin if there is a hole.
9885 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009886
Richard Smitha5370fb2017-12-08 22:57:11 +00009887 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9888 if (R.Width == 0)
9889 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9890 else if (R.Width >= BitWidth && !Unsigned) {
9891 // Promotion made the type *narrower*. This happens when promoting
9892 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9893 // Treat all values of 'signed int' as being in range for now.
9894 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9895 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9896 } else {
9897 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9898 .extOrTrunc(BitWidth);
9899 PromotedMin.setIsUnsigned(Unsigned);
9900
9901 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9902 .extOrTrunc(BitWidth);
9903 PromotedMax.setIsUnsigned(Unsigned);
9904 }
9905 }
9906
9907 // Determine whether this range is contiguous (has no hole).
9908 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9909
9910 // Where a constant value is within the range.
9911 enum ComparisonResult {
9912 LT = 0x1,
9913 LE = 0x2,
9914 GT = 0x4,
9915 GE = 0x8,
9916 EQ = 0x10,
9917 NE = 0x20,
9918 InRangeFlag = 0x40,
9919
9920 Less = LE | LT | NE,
9921 Min = LE | InRangeFlag,
9922 InRange = InRangeFlag,
9923 Max = GE | InRangeFlag,
9924 Greater = GE | GT | NE,
9925
9926 OnlyValue = LE | GE | EQ | InRangeFlag,
9927 InHole = NE
9928 };
9929
9930 ComparisonResult compare(const llvm::APSInt &Value) const {
9931 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9932 Value.isUnsigned() == PromotedMin.isUnsigned());
9933 if (!isContiguous()) {
9934 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9935 if (Value.isMinValue()) return Min;
9936 if (Value.isMaxValue()) return Max;
9937 if (Value >= PromotedMin) return InRange;
9938 if (Value <= PromotedMax) return InRange;
9939 return InHole;
9940 }
9941
9942 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9943 case -1: return Less;
9944 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9945 case 1:
9946 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9947 case -1: return InRange;
9948 case 0: return Max;
9949 case 1: return Greater;
9950 }
9951 }
9952
9953 llvm_unreachable("impossible compare result");
9954 }
9955
Richard Smithc70f1d62017-12-14 15:16:18 +00009956 static llvm::Optional<StringRef>
9957 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9958 if (Op == BO_Cmp) {
9959 ComparisonResult LTFlag = LT, GTFlag = GT;
9960 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9961
9962 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9963 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9964 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9965 return llvm::None;
9966 }
9967
Richard Smitha5370fb2017-12-08 22:57:11 +00009968 ComparisonResult TrueFlag, FalseFlag;
9969 if (Op == BO_EQ) {
9970 TrueFlag = EQ;
9971 FalseFlag = NE;
9972 } else if (Op == BO_NE) {
9973 TrueFlag = NE;
9974 FalseFlag = EQ;
9975 } else {
9976 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9977 TrueFlag = LT;
9978 FalseFlag = GE;
9979 } else {
9980 TrueFlag = GT;
9981 FalseFlag = LE;
9982 }
9983 if (Op == BO_GE || Op == BO_LE)
9984 std::swap(TrueFlag, FalseFlag);
9985 }
9986 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009987 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009988 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009989 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009990 return llvm::None;
9991 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009992};
John McCallcc7e5bf2010-05-06 08:58:33 +00009993}
9994
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009995static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009996 // Strip off implicit integral promotions.
9997 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009998 if (ICE->getCastKind() != CK_IntegralCast &&
9999 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +000010000 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +000010001 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +000010002 }
10003
10004 return E->getType()->isEnumeralType();
10005}
10006
Richard Smith692f66ab2017-12-06 19:23:19 +000010007static int classifyConstantValue(Expr *Constant) {
10008 // The values of this enumeration are used in the diagnostics
10009 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10010 enum ConstantValueKind {
10011 Miscellaneous = 0,
10012 LiteralTrue,
10013 LiteralFalse
10014 };
10015 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10016 return BL->getValue() ? ConstantValueKind::LiteralTrue
10017 : ConstantValueKind::LiteralFalse;
10018 return ConstantValueKind::Miscellaneous;
10019}
10020
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010021static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10022 Expr *Constant, Expr *Other,
10023 const llvm::APSInt &Value,
10024 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010025 if (S.inTemplateInstantiation())
10026 return false;
10027
Richard Smitha5370fb2017-12-08 22:57:11 +000010028 Expr *OriginalOther = Other;
10029
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010030 Constant = Constant->IgnoreParenImpCasts();
10031 Other = Other->IgnoreParenImpCasts();
10032
Richard Smitha5370fb2017-12-08 22:57:11 +000010033 // Suppress warnings on tautological comparisons between values of the same
10034 // enumeration type. There are only two ways we could warn on this:
10035 // - If the constant is outside the range of representable values of
10036 // the enumeration. In such a case, we should warn about the cast
10037 // to enumeration type, not about the comparison.
10038 // - If the constant is the maximum / minimum in-range value. For an
10039 // enumeratin type, such comparisons can be meaningful and useful.
10040 if (Constant->getType()->isEnumeralType() &&
10041 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10042 return false;
10043
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010044 // TODO: Investigate using GetExprRange() to get tighter bounds
10045 // on the bit ranges.
10046 QualType OtherT = Other->getType();
10047 if (const auto *AT = OtherT->getAs<AtomicType>())
10048 OtherT = AT->getValueType();
10049 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10050
10051 // Whether we're treating Other as being a bool because of the form of
10052 // expression despite it having another type (typically 'int' in C).
10053 bool OtherIsBooleanDespiteType =
10054 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10055 if (OtherIsBooleanDespiteType)
10056 OtherRange = IntRange::forBoolType();
10057
Richard Smitha5370fb2017-12-08 22:57:11 +000010058 // Determine the promoted range of the other type and see if a comparison of
10059 // the constant against that range is tautological.
10060 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10061 Value.isUnsigned());
10062 auto Cmp = OtherPromotedRange.compare(Value);
10063 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10064 if (!Result)
10065 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +000010066
Richard Smitha5370fb2017-12-08 22:57:11 +000010067 // Suppress the diagnostic for an in-range comparison if the constant comes
10068 // from a macro or enumerator. We don't want to diagnose
10069 //
10070 // some_long_value <= INT_MAX
10071 //
10072 // when sizeof(int) == sizeof(long).
10073 bool InRange = Cmp & PromotedRange::InRangeFlag;
10074 if (InRange && IsEnumConstOrFromMacro(S, Constant))
10075 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010076
10077 // If this is a comparison to an enum constant, include that
10078 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +000010079 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010080 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10081 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10082
Richard Smitha5370fb2017-12-08 22:57:11 +000010083 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010084 SmallString<64> PrettySourceValue;
10085 llvm::raw_svector_ostream OS(PrettySourceValue);
10086 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +000010087 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010088 else
10089 OS << Value;
10090
Richard Smitha5370fb2017-12-08 22:57:11 +000010091 // FIXME: We use a somewhat different formatting for the in-range cases and
10092 // cases involving boolean values for historical reasons. We should pick a
10093 // consistent way of presenting these diagnostics.
10094 if (!InRange || Other->isKnownToHaveBooleanValue()) {
10095 S.DiagRuntimeBehavior(
10096 E->getOperatorLoc(), E,
10097 S.PDiag(!InRange ? diag::warn_out_of_range_compare
10098 : diag::warn_tautological_bool_compare)
10099 << OS.str() << classifyConstantValue(Constant)
10100 << OtherT << OtherIsBooleanDespiteType << *Result
10101 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10102 } else {
10103 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10104 ? (HasEnumType(OriginalOther)
10105 ? diag::warn_unsigned_enum_always_true_comparison
10106 : diag::warn_unsigned_always_true_comparison)
10107 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +000010108
Richard Smitha5370fb2017-12-08 22:57:11 +000010109 S.Diag(E->getOperatorLoc(), Diag)
10110 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10111 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10112 }
10113
10114 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010115}
10116
John McCallcc7e5bf2010-05-06 08:58:33 +000010117/// Analyze the operands of the given comparison. Implements the
10118/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010119static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +000010120 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10121 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010122}
John McCall263a48b2010-01-04 23:31:57 +000010123
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010124/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +000010125///
Richard Trieu82402a02011-09-15 21:56:47 +000010126/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010127static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010128 // The type the comparison is being performed in.
10129 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +000010130
10131 // Only analyze comparison operators where both sides have been converted to
10132 // the same type.
10133 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10134 return AnalyzeImpConvsInComparison(S, E);
10135
10136 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +000010137 if (E->isValueDependent())
10138 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010139
Roman Lebedev6de129e2017-10-15 20:13:17 +000010140 Expr *LHS = E->getLHS();
10141 Expr *RHS = E->getRHS();
10142
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010143 if (T->isIntegralType(S.Context)) {
10144 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010145 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010146
Roman Lebedev6de129e2017-10-15 20:13:17 +000010147 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10148 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +000010149
Roman Lebedev6de129e2017-10-15 20:13:17 +000010150 // We don't care about expressions whose result is a constant.
10151 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10152 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +000010153
Roman Lebedev6de129e2017-10-15 20:13:17 +000010154 // We only care about expressions where just one side is literal
10155 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10156 // Is the constant on the RHS or LHS?
10157 const bool RhsConstant = IsRHSIntegralLiteral;
10158 Expr *Const = RhsConstant ? RHS : LHS;
10159 Expr *Other = RhsConstant ? LHS : RHS;
10160 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10161
10162 // Check whether an integer constant comparison results in a value
10163 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +000010164 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10165 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010166 }
10167 }
10168
10169 if (!T->hasUnsignedIntegerRepresentation()) {
10170 // We don't do anything special if this isn't an unsigned integral
10171 // comparison: we're only interested in integral comparisons, and
10172 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +000010173 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010174 }
10175
10176 LHS = LHS->IgnoreParenImpCasts();
10177 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010178
Alex Lorenzb57409f2018-02-07 20:45:39 +000010179 if (!S.getLangOpts().CPlusPlus) {
10180 // Avoid warning about comparison of integers with different signs when
10181 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10182 // the type of `E`.
10183 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10184 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10185 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10186 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10187 }
10188
John McCallcc7e5bf2010-05-06 08:58:33 +000010189 // Check to see if one of the (unmodified) operands is of different
10190 // signedness.
10191 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +000010192 if (LHS->getType()->hasSignedIntegerRepresentation()) {
10193 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +000010194 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +000010195 signedOperand = LHS;
10196 unsignedOperand = RHS;
10197 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10198 signedOperand = RHS;
10199 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +000010200 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +000010201 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010202 }
10203
John McCallcc7e5bf2010-05-06 08:58:33 +000010204 // Otherwise, calculate the effective range of the signed operand.
10205 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +000010206
John McCallcc7e5bf2010-05-06 08:58:33 +000010207 // Go ahead and analyze implicit conversions in the operands. Note
10208 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +000010209 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10210 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +000010211
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010212 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +000010213 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010214 return;
John McCallca01b222010-01-04 23:21:16 +000010215
10216 // For (in)equality comparisons, if the unsigned operand is a
10217 // constant which cannot collide with a overflowed signed operand,
10218 // then reinterpreting the signed operand as unsigned will not
10219 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +000010220 if (E->isEqualityOp()) {
10221 unsigned comparisonWidth = S.Context.getIntWidth(T);
10222 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +000010223
John McCallcc7e5bf2010-05-06 08:58:33 +000010224 // We should never be unable to prove that the unsigned operand is
10225 // non-negative.
10226 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10227
10228 if (unsignedRange.Width < comparisonWidth)
10229 return;
10230 }
10231
Douglas Gregorbfb4a212012-05-01 01:53:49 +000010232 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10233 S.PDiag(diag::warn_mixed_sign_comparison)
10234 << LHS->getType() << RHS->getType()
10235 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +000010236}
10237
John McCall1f425642010-11-11 03:21:53 +000010238/// Analyzes an attempt to assign the given value to a bitfield.
10239///
10240/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010241static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10242 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +000010243 assert(Bitfield->isBitField());
10244 if (Bitfield->isInvalidDecl())
10245 return false;
10246
John McCalldeebbcf2010-11-11 05:33:51 +000010247 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +000010248 QualType BitfieldType = Bitfield->getType();
10249 if (BitfieldType->isBooleanType())
10250 return false;
10251
10252 if (BitfieldType->isEnumeralType()) {
10253 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10254 // If the underlying enum type was not explicitly specified as an unsigned
10255 // type and the enum contain only positive values, MSVC++ will cause an
10256 // inconsistency by storing this as a signed type.
10257 if (S.getLangOpts().CPlusPlus11 &&
10258 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10259 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10260 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10261 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10262 << BitfieldEnumDecl->getNameAsString();
10263 }
10264 }
10265
John McCalldeebbcf2010-11-11 05:33:51 +000010266 if (Bitfield->getType()->isBooleanType())
10267 return false;
10268
Douglas Gregor789adec2011-02-04 13:09:01 +000010269 // Ignore value- or type-dependent expressions.
10270 if (Bitfield->getBitWidth()->isValueDependent() ||
10271 Bitfield->getBitWidth()->isTypeDependent() ||
10272 Init->isValueDependent() ||
10273 Init->isTypeDependent())
10274 return false;
10275
John McCall1f425642010-11-11 03:21:53 +000010276 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +000010277 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +000010278
Fangrui Song407659a2018-11-30 23:41:18 +000010279 Expr::EvalResult Result;
10280 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
Reid Kleckner329f24d2017-03-14 18:01:02 +000010281 Expr::SE_AllowSideEffects)) {
10282 // The RHS is not constant. If the RHS has an enum type, make sure the
10283 // bitfield is wide enough to hold all the values of the enum without
10284 // truncation.
10285 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10286 EnumDecl *ED = EnumTy->getDecl();
10287 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10288
10289 // Enum types are implicitly signed on Windows, so check if there are any
10290 // negative enumerators to see if the enum was intended to be signed or
10291 // not.
10292 bool SignedEnum = ED->getNumNegativeBits() > 0;
10293
10294 // Check for surprising sign changes when assigning enum values to a
10295 // bitfield of different signedness. If the bitfield is signed and we
10296 // have exactly the right number of bits to store this unsigned enum,
10297 // suggest changing the enum to an unsigned type. This typically happens
10298 // on Windows where unfixed enums always use an underlying type of 'int'.
10299 unsigned DiagID = 0;
10300 if (SignedEnum && !SignedBitfield) {
10301 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10302 } else if (SignedBitfield && !SignedEnum &&
10303 ED->getNumPositiveBits() == FieldWidth) {
10304 DiagID = diag::warn_signed_bitfield_enum_conversion;
10305 }
10306
10307 if (DiagID) {
10308 S.Diag(InitLoc, DiagID) << Bitfield << ED;
10309 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10310 SourceRange TypeRange =
10311 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10312 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10313 << SignedEnum << TypeRange;
10314 }
10315
10316 // Compute the required bitwidth. If the enum has negative values, we need
10317 // one more bit than the normal number of positive bits to represent the
10318 // sign bit.
10319 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10320 ED->getNumNegativeBits())
10321 : ED->getNumPositiveBits();
10322
10323 // Check the bitwidth.
10324 if (BitsNeeded > FieldWidth) {
10325 Expr *WidthExpr = Bitfield->getBitWidth();
10326 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10327 << Bitfield << ED;
10328 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10329 << BitsNeeded << ED << WidthExpr->getSourceRange();
10330 }
10331 }
10332
John McCall1f425642010-11-11 03:21:53 +000010333 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +000010334 }
John McCall1f425642010-11-11 03:21:53 +000010335
Fangrui Song407659a2018-11-30 23:41:18 +000010336 llvm::APSInt Value = Result.Val.getInt();
10337
John McCall1f425642010-11-11 03:21:53 +000010338 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +000010339
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010340 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +000010341 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010342 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10343 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +000010344
John McCall1f425642010-11-11 03:21:53 +000010345 if (OriginalWidth <= FieldWidth)
10346 return false;
10347
Eli Friedmanc267a322012-01-26 23:11:39 +000010348 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +000010349 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +000010350 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +000010351
Eli Friedmanc267a322012-01-26 23:11:39 +000010352 // Check whether the stored value is equal to the original value.
10353 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +000010354 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +000010355 return false;
10356
Eli Friedmanc267a322012-01-26 23:11:39 +000010357 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +000010358 // therefore don't strictly fit into a signed bitfield of width 1.
10359 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +000010360 return false;
10361
John McCall1f425642010-11-11 03:21:53 +000010362 std::string PrettyValue = Value.toString(10);
10363 std::string PrettyTrunc = TruncatedValue.toString(10);
10364
10365 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10366 << PrettyValue << PrettyTrunc << OriginalInit->getType()
10367 << Init->getSourceRange();
10368
10369 return true;
10370}
10371
John McCalld2a53122010-11-09 23:24:47 +000010372/// Analyze the given simple or compound assignment for warning-worthy
10373/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010374static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +000010375 // Just recurse on the LHS.
10376 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10377
10378 // We want to recurse on the RHS as normal unless we're assigning to
10379 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +000010380 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010381 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +000010382 E->getOperatorLoc())) {
10383 // Recurse, ignoring any implicit conversions on the RHS.
10384 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10385 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +000010386 }
10387 }
10388
10389 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
Richard Smith6822bd72018-10-26 19:26:45 +000010390
JF Bastiene77b48b2018-09-10 20:42:56 +000010391 // Diagnose implicitly sequentially-consistent atomic assignment.
10392 if (E->getLHS()->getType()->isAtomicType())
10393 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCalld2a53122010-11-09 23:24:47 +000010394}
10395
John McCall263a48b2010-01-04 23:31:57 +000010396/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Fangrui Song6907ce22018-07-30 19:24:48 +000010397static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010398 SourceLocation CContext, unsigned diag,
10399 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010400 if (pruneControlFlow) {
10401 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10402 S.PDiag(diag)
10403 << SourceType << T << E->getSourceRange()
10404 << SourceRange(CContext));
10405 return;
10406 }
Douglas Gregor364f7db2011-03-12 00:14:31 +000010407 S.Diag(E->getExprLoc(), diag)
10408 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10409}
10410
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010411/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010412static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10413 SourceLocation CContext,
10414 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010415 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010416}
10417
Richard Trieube234c32016-04-21 21:04:55 +000010418/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010419static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10420 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +000010421 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +000010422 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +000010423
10424 Expr *InnerE = E->IgnoreParenImpCasts();
10425 // We also want to warn on, e.g., "int i = -1.234"
10426 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10427 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10428 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10429
10430 const bool IsLiteral =
10431 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10432
10433 llvm::APFloat Value(0.0);
10434 bool IsConstant =
10435 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10436 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +000010437 return DiagnoseImpCast(S, E, T, CContext,
10438 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +000010439 }
10440
Chandler Carruth016ef402011-04-10 08:36:24 +000010441 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +000010442
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +000010443 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10444 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +000010445 llvm::APFloat::opStatus Result = Value.convertToInteger(
10446 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10447
10448 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +000010449 if (IsLiteral) return;
10450 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10451 PruneWarnings);
10452 }
10453
Erich Keanea4c48c62018-05-08 21:26:21 +000010454 // Conversion of a floating-point value to a non-bool integer where the
10455 // integral part cannot be represented by the integer type is undefined.
10456 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10457 return DiagnoseImpCast(
10458 S, E, T, CContext,
10459 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +000010460 : diag::warn_impcast_float_to_integer_out_of_range,
10461 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +000010462
Richard Trieube234c32016-04-21 21:04:55 +000010463 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +000010464 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +000010465 // Warn on floating point literal to integer.
10466 DiagID = diag::warn_impcast_literal_float_to_integer;
10467 } else if (IntegerValue == 0) {
10468 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
10469 return DiagnoseImpCast(S, E, T, CContext,
10470 diag::warn_impcast_float_integer, PruneWarnings);
10471 }
10472 // Warn on non-zero to zero conversion.
10473 DiagID = diag::warn_impcast_float_to_integer_zero;
10474 } else {
10475 if (IntegerValue.isUnsigned()) {
10476 if (!IntegerValue.isMaxValue()) {
10477 return DiagnoseImpCast(S, E, T, CContext,
10478 diag::warn_impcast_float_integer, PruneWarnings);
10479 }
10480 } else { // IntegerValue.isSigned()
10481 if (!IntegerValue.isMaxSignedValue() &&
10482 !IntegerValue.isMinSignedValue()) {
10483 return DiagnoseImpCast(S, E, T, CContext,
10484 diag::warn_impcast_float_integer, PruneWarnings);
10485 }
10486 }
10487 // Warn on evaluatable floating point expression to integer conversion.
10488 DiagID = diag::warn_impcast_float_to_integer;
10489 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010490
David Bolvansky3cc2ef82018-11-14 14:27:51 +000010491 // FIXME: Force the precision of the source value down so we don't print
10492 // digits which are usually useless (we don't really care here if we
10493 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
10494 // would automatically print the shortest representation, but it's a bit
10495 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +000010496 SmallString<16> PrettySourceValue;
David Bolvansky3cc2ef82018-11-14 14:27:51 +000010497 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10498 precision = (precision * 59 + 195) / 196;
10499 Value.toString(PrettySourceValue, precision);
Eli Friedman07185912013-08-29 23:44:43 +000010500
David Blaikie9b88cc02012-05-15 17:18:27 +000010501 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +000010502 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +000010503 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +000010504 else
David Blaikie9b88cc02012-05-15 17:18:27 +000010505 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +000010506
Richard Trieube234c32016-04-21 21:04:55 +000010507 if (PruneWarnings) {
10508 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10509 S.PDiag(DiagID)
10510 << E->getType() << T.getUnqualifiedType()
10511 << PrettySourceValue << PrettyTargetValue
10512 << E->getSourceRange() << SourceRange(CContext));
10513 } else {
10514 S.Diag(E->getExprLoc(), DiagID)
10515 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10516 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10517 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010518}
10519
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010520/// Analyze the given compound assignment for the possible losing of
10521/// floating-point precision.
10522static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10523 assert(isa<CompoundAssignOperator>(E) &&
10524 "Must be compound assignment operation");
10525 // Recurse on the LHS and RHS in here
10526 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10527 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10528
JF Bastiene77b48b2018-09-10 20:42:56 +000010529 if (E->getLHS()->getType()->isAtomicType())
10530 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10531
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010532 // Now check the outermost expression
10533 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10534 const auto *RBT = cast<CompoundAssignOperator>(E)
10535 ->getComputationResultType()
10536 ->getAs<BuiltinType>();
10537
10538 // The below checks assume source is floating point.
10539 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10540
10541 // If source is floating point but target is not.
10542 if (!ResultBT->isFloatingPoint())
10543 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(),
10544 E->getExprLoc());
10545
10546 // If both source and target are floating points.
10547 // Builtin FP kinds are ordered by increasing FP rank.
10548 if (ResultBT->getKind() < RBT->getKind() &&
10549 // We don't want to warn for system macro.
10550 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10551 // warn about dropping FP rank.
10552 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10553 diag::warn_impcast_float_result_precision);
10554}
10555
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010556static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10557 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +000010558 if (!Range.Width) return "0";
10559
10560 llvm::APSInt ValueInRange = Value;
10561 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +000010562 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +000010563 return ValueInRange.toString(10);
10564}
10565
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010566static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010567 if (!isa<ImplicitCastExpr>(Ex))
10568 return false;
10569
10570 Expr *InnerE = Ex->IgnoreParenImpCasts();
10571 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10572 const Type *Source =
10573 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10574 if (Target->isDependentType())
10575 return false;
10576
10577 const BuiltinType *FloatCandidateBT =
10578 dyn_cast<BuiltinType>(ToBool ? Source : Target);
10579 const Type *BoolCandidateType = ToBool ? Target : Source;
10580
10581 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10582 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10583}
10584
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010585static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10586 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010587 unsigned NumArgs = TheCall->getNumArgs();
10588 for (unsigned i = 0; i < NumArgs; ++i) {
10589 Expr *CurrA = TheCall->getArg(i);
10590 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10591 continue;
10592
10593 bool IsSwapped = ((i > 0) &&
10594 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10595 IsSwapped |= ((i < (NumArgs - 1)) &&
10596 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10597 if (IsSwapped) {
10598 // Warn on this floating-point to bool conversion.
10599 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10600 CurrA->getType(), CC,
10601 diag::warn_impcast_floating_point_to_bool);
10602 }
10603 }
10604}
10605
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010606static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10607 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +000010608 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10609 E->getExprLoc()))
10610 return;
10611
Richard Trieu09d6b802016-01-08 23:35:06 +000010612 // Don't warn on functions which have return type nullptr_t.
10613 if (isa<CallExpr>(E))
10614 return;
10615
Richard Trieu5b993502014-10-15 03:42:06 +000010616 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10617 const Expr::NullPointerConstantKind NullKind =
10618 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10619 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10620 return;
10621
10622 // Return if target type is a safe conversion.
10623 if (T->isAnyPointerType() || T->isBlockPointerType() ||
10624 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10625 return;
10626
10627 SourceLocation Loc = E->getSourceRange().getBegin();
10628
Richard Trieu0a5e1662016-02-13 00:58:53 +000010629 // Venture through the macro stacks to get to the source of macro arguments.
10630 // The new location is a better location than the complete location that was
10631 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +000010632 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10633 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +000010634
Richard Trieu5b993502014-10-15 03:42:06 +000010635 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +000010636 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10637 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10638 Loc, S.SourceMgr, S.getLangOpts());
10639 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +000010640 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +000010641 }
10642
10643 // Only warn if the null and context location are in the same macro expansion.
10644 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10645 return;
10646
10647 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010648 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000010649 << FixItHint::CreateReplacement(Loc,
10650 S.getFixItZeroLiteralForType(T, Loc));
10651}
10652
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010653static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10654 ObjCArrayLiteral *ArrayLiteral);
10655
10656static void
10657checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10658 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000010659
10660/// Check a single element within a collection literal against the
10661/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010662static void checkObjCCollectionLiteralElement(Sema &S,
10663 QualType TargetElementType,
10664 Expr *Element,
10665 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010666 // Skip a bitcast to 'id' or qualified 'id'.
10667 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10668 if (ICE->getCastKind() == CK_BitCast &&
10669 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10670 Element = ICE->getSubExpr();
10671 }
10672
10673 QualType ElementType = Element->getType();
10674 ExprResult ElementResult(Element);
10675 if (ElementType->getAs<ObjCObjectPointerType>() &&
10676 S.CheckSingleAssignmentConstraints(TargetElementType,
10677 ElementResult,
10678 false, false)
10679 != Sema::Compatible) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010680 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10681 << ElementType << ElementKind << TargetElementType
10682 << Element->getSourceRange();
Douglas Gregor5054cb02015-07-07 03:58:22 +000010683 }
10684
10685 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10686 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10687 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10688 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10689}
10690
10691/// Check an Objective-C array literal being converted to the given
10692/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010693static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10694 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010695 if (!S.NSArrayDecl)
10696 return;
10697
10698 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10699 if (!TargetObjCPtr)
10700 return;
10701
10702 if (TargetObjCPtr->isUnspecialized() ||
10703 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10704 != S.NSArrayDecl->getCanonicalDecl())
10705 return;
10706
10707 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10708 if (TypeArgs.size() != 1)
10709 return;
10710
10711 QualType TargetElementType = TypeArgs[0];
10712 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10713 checkObjCCollectionLiteralElement(S, TargetElementType,
10714 ArrayLiteral->getElement(I),
10715 0);
10716 }
10717}
10718
10719/// Check an Objective-C dictionary literal being converted to the given
10720/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010721static void
10722checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10723 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010724 if (!S.NSDictionaryDecl)
10725 return;
10726
10727 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10728 if (!TargetObjCPtr)
10729 return;
10730
10731 if (TargetObjCPtr->isUnspecialized() ||
10732 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10733 != S.NSDictionaryDecl->getCanonicalDecl())
10734 return;
10735
10736 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10737 if (TypeArgs.size() != 2)
10738 return;
10739
10740 QualType TargetKeyType = TypeArgs[0];
10741 QualType TargetObjectType = TypeArgs[1];
10742 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10743 auto Element = DictionaryLiteral->getKeyValueElement(I);
10744 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10745 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10746 }
10747}
10748
Richard Trieufc404c72016-02-05 23:02:38 +000010749// Helper function to filter out cases for constant width constant conversion.
10750// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010751static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10752 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010753 // If initializing from a constant, and the constant starts with '0',
10754 // then it is a binary, octal, or hexadecimal. Allow these constants
10755 // to fill all the bits, even if there is a sign change.
10756 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10757 const char FirstLiteralCharacter =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010758 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
Richard Trieufc404c72016-02-05 23:02:38 +000010759 if (FirstLiteralCharacter == '0')
10760 return false;
10761 }
10762
10763 // If the CC location points to a '{', and the type is char, then assume
10764 // assume it is an array initialization.
10765 if (CC.isValid() && T->isCharType()) {
10766 const char FirstContextCharacter =
10767 S.getSourceManager().getCharacterData(CC)[0];
10768 if (FirstContextCharacter == '{')
10769 return false;
10770 }
10771
10772 return true;
10773}
10774
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010775static void
10776CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10777 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010778 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010779
John McCallcc7e5bf2010-05-06 08:58:33 +000010780 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10781 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10782 if (Source == Target) return;
10783 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010784
Chandler Carruthc22845a2011-07-26 05:40:03 +000010785 // If the conversion context location is invalid don't complain. We also
10786 // don't want to emit a warning if the issue occurs from the expansion of
10787 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10788 // delay this check as long as possible. Once we detect we are in that
10789 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010790 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010791 return;
10792
JF Bastiene77b48b2018-09-10 20:42:56 +000010793 if (Source->isAtomicType())
10794 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10795
Richard Trieu021baa32011-09-23 20:10:00 +000010796 // Diagnose implicit casts to bool.
10797 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10798 if (isa<StringLiteral>(E))
10799 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010800 // and expressions, for instance, assert(0 && "error here"), are
10801 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010802 return DiagnoseImpCast(S, E, T, CC,
10803 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010804 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10805 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10806 // This covers the literal expressions that evaluate to Objective-C
10807 // objects.
10808 return DiagnoseImpCast(S, E, T, CC,
10809 diag::warn_impcast_objective_c_literal_to_bool);
10810 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010811 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10812 // Warn on pointer to bool conversion that is always true.
10813 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10814 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010815 }
Richard Trieu021baa32011-09-23 20:10:00 +000010816 }
John McCall263a48b2010-01-04 23:31:57 +000010817
Douglas Gregor5054cb02015-07-07 03:58:22 +000010818 // Check implicit casts from Objective-C collection literals to specialized
10819 // collection types, e.g., NSArray<NSString *> *.
10820 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10821 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10822 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10823 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10824
John McCall263a48b2010-01-04 23:31:57 +000010825 // Strip vector types.
10826 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010827 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010828 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010829 return;
John McCallacf0ee52010-10-08 02:01:28 +000010830 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010831 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010832
Chris Lattneree7286f2011-06-14 04:51:15 +000010833 // If the vector cast is cast between two vectors of the same size, it is
10834 // a bitcast, not a conversion.
10835 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10836 return;
John McCall263a48b2010-01-04 23:31:57 +000010837
10838 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10839 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10840 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010841 if (auto VecTy = dyn_cast<VectorType>(Target))
10842 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010843
10844 // Strip complex types.
10845 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010846 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010847 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010848 return;
10849
Tim Northover02416372017-08-08 23:18:05 +000010850 return DiagnoseImpCast(S, E, T, CC,
10851 S.getLangOpts().CPlusPlus
10852 ? diag::err_impcast_complex_scalar
10853 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010854 }
John McCall263a48b2010-01-04 23:31:57 +000010855
10856 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10857 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10858 }
10859
10860 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10861 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10862
10863 // If the source is floating point...
10864 if (SourceBT && SourceBT->isFloatingPoint()) {
10865 // ...and the target is floating point...
10866 if (TargetBT && TargetBT->isFloatingPoint()) {
10867 // ...then warn if we're dropping FP rank.
10868
10869 // Builtin FP kinds are ordered by increasing FP rank.
10870 if (SourceBT->getKind() > TargetBT->getKind()) {
10871 // Don't warn about float constants that are precisely
10872 // representable in the target type.
10873 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010874 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010875 // Value might be a float, a float vector, or a float complex.
10876 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010877 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10878 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010879 return;
10880 }
10881
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010882 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010883 return;
10884
John McCallacf0ee52010-10-08 02:01:28 +000010885 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010886 }
10887 // ... or possibly if we're increasing rank, too
10888 else if (TargetBT->getKind() > SourceBT->getKind()) {
10889 if (S.SourceMgr.isInSystemMacro(CC))
10890 return;
10891
10892 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010893 }
10894 return;
10895 }
10896
Richard Trieube234c32016-04-21 21:04:55 +000010897 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010898 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010899 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010900 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010901
Richard Trieube234c32016-04-21 21:04:55 +000010902 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010903 }
John McCall263a48b2010-01-04 23:31:57 +000010904
Richard Smith54894fd2015-12-30 01:06:52 +000010905 // Detect the case where a call result is converted from floating-point to
10906 // to bool, and the final argument to the call is converted from bool, to
10907 // discover this typo:
10908 //
10909 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10910 //
10911 // FIXME: This is an incredibly special case; is there some more general
10912 // way to detect this class of misplaced-parentheses bug?
10913 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010914 // Check last argument of function call to see if it is an
10915 // implicit cast from a type matching the type the result
10916 // is being cast to.
10917 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010918 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010919 Expr *LastA = CEx->getArg(NumArgs - 1);
10920 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010921 if (isa<ImplicitCastExpr>(LastA) &&
10922 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010923 // Warn on this floating-point to bool conversion
10924 DiagnoseImpCast(S, E, T, CC,
10925 diag::warn_impcast_floating_point_to_bool);
10926 }
10927 }
10928 }
John McCall263a48b2010-01-04 23:31:57 +000010929 return;
10930 }
10931
Richard Trieu5b993502014-10-15 03:42:06 +000010932 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010933
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010934 S.DiscardMisalignedMemberAddress(Target, E);
10935
David Blaikie9366d2b2012-06-19 21:19:06 +000010936 if (!Source->isIntegerType() || !Target->isIntegerType())
10937 return;
10938
David Blaikie7555b6a2012-05-15 16:56:36 +000010939 // TODO: remove this early return once the false positives for constant->bool
10940 // in templates, macros, etc, are reduced or removed.
10941 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10942 return;
10943
John McCallcc7e5bf2010-05-06 08:58:33 +000010944 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010945 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010946
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010947 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010948 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010949 // TODO: this should happen for bitfield stores, too.
Fangrui Song407659a2018-11-30 23:41:18 +000010950 Expr::EvalResult Result;
10951 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
10952 llvm::APSInt Value(32);
10953 Value = Result.Val.getInt();
10954
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010955 if (S.SourceMgr.isInSystemMacro(CC))
10956 return;
10957
John McCall18a2c2c2010-11-09 22:22:12 +000010958 std::string PrettySourceValue = Value.toString(10);
10959 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010960
Ted Kremenek33ba9952011-10-22 02:37:33 +000010961 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10962 S.PDiag(diag::warn_impcast_integer_precision_constant)
10963 << PrettySourceValue << PrettyTargetValue
10964 << E->getType() << T << E->getSourceRange()
10965 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010966 return;
10967 }
10968
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010969 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10970 if (S.SourceMgr.isInSystemMacro(CC))
10971 return;
10972
David Blaikie9455da02012-04-12 22:40:54 +000010973 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010974 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10975 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010976 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010977 }
10978
David Bolvanskycf7d2252018-10-02 06:02:30 +000010979 if (TargetRange.Width > SourceRange.Width) {
10980 if (auto *UO = dyn_cast<UnaryOperator>(E))
10981 if (UO->getOpcode() == UO_Minus)
10982 if (Source->isUnsignedIntegerType()) {
10983 if (Target->isUnsignedIntegerType())
10984 return DiagnoseImpCast(S, E, T, CC,
10985 diag::warn_impcast_high_order_zero_bits);
10986 if (Target->isSignedIntegerType())
10987 return DiagnoseImpCast(S, E, T, CC,
10988 diag::warn_impcast_nonnegative_result);
10989 }
10990 }
10991
Richard Trieudcb55572016-01-29 23:51:16 +000010992 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10993 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10994 // Warn when doing a signed to signed conversion, warn if the positive
10995 // source value is exactly the width of the target type, which will
10996 // cause a negative value to be stored.
10997
Fangrui Song407659a2018-11-30 23:41:18 +000010998 Expr::EvalResult Result;
10999 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
Richard Trieufc404c72016-02-05 23:02:38 +000011000 !S.SourceMgr.isInSystemMacro(CC)) {
Fangrui Song407659a2018-11-30 23:41:18 +000011001 llvm::APSInt Value = Result.Val.getInt();
Richard Trieufc404c72016-02-05 23:02:38 +000011002 if (isSameWidthConstantConversion(S, E, T, CC)) {
11003 std::string PrettySourceValue = Value.toString(10);
11004 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000011005
Richard Trieufc404c72016-02-05 23:02:38 +000011006 S.DiagRuntimeBehavior(
11007 E->getExprLoc(), E,
11008 S.PDiag(diag::warn_impcast_integer_precision_constant)
11009 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11010 << E->getSourceRange() << clang::SourceRange(CC));
11011 return;
Richard Trieudcb55572016-01-29 23:51:16 +000011012 }
11013 }
Richard Trieufc404c72016-02-05 23:02:38 +000011014
Richard Trieudcb55572016-01-29 23:51:16 +000011015 // Fall through for non-constants to give a sign conversion warning.
11016 }
11017
John McCallcc7e5bf2010-05-06 08:58:33 +000011018 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11019 (!TargetRange.NonNegative && SourceRange.NonNegative &&
11020 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011021 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011022 return;
11023
John McCallcc7e5bf2010-05-06 08:58:33 +000011024 unsigned DiagID = diag::warn_impcast_integer_sign;
11025
11026 // Traditionally, gcc has warned about this under -Wsign-compare.
11027 // We also want to warn about it in -Wconversion.
11028 // So if -Wconversion is off, use a completely identical diagnostic
11029 // in the sign-compare group.
Fangrui Song6907ce22018-07-30 19:24:48 +000011030 // The conditional-checking code will
John McCallcc7e5bf2010-05-06 08:58:33 +000011031 if (ICContext) {
11032 DiagID = diag::warn_impcast_integer_sign_conditional;
11033 *ICContext = true;
11034 }
11035
John McCallacf0ee52010-10-08 02:01:28 +000011036 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000011037 }
11038
Douglas Gregora78f1932011-02-22 02:45:07 +000011039 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000011040 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11041 // type, to give us better diagnostics.
11042 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011043 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000011044 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11045 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11046 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11047 SourceType = S.Context.getTypeDeclType(Enum);
11048 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11049 }
11050 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011051
Douglas Gregora78f1932011-02-22 02:45:07 +000011052 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11053 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000011054 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11055 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011056 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011057 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011058 return;
11059
Fangrui Song6907ce22018-07-30 19:24:48 +000011060 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000011061 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011062 }
John McCall263a48b2010-01-04 23:31:57 +000011063}
11064
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011065static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11066 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011067
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011068static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11069 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011070 E = E->IgnoreParenImpCasts();
11071
11072 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000011073 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011074
John McCallacf0ee52010-10-08 02:01:28 +000011075 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011076 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011077 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000011078}
11079
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011080static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11081 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000011082 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000011083
11084 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000011085 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11086 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011087
11088 // If -Wconversion would have warned about either of the candidates
11089 // for a signedness conversion to the context type...
11090 if (!Suspicious) return;
11091
11092 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011093 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000011094 return;
11095
John McCallcc7e5bf2010-05-06 08:58:33 +000011096 // ...then check whether it would have warned about either of the
11097 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000011098 if (E->getType() == T) return;
Fangrui Song6907ce22018-07-30 19:24:48 +000011099
Richard Trieubb43dec2011-07-21 02:46:28 +000011100 Suspicious = false;
11101 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11102 E->getType(), CC, &Suspicious);
11103 if (!Suspicious)
11104 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000011105 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011106}
11107
JF Bastiene77b48b2018-09-10 20:42:56 +000011108/// Check conversion of given expression to boolean.
Richard Trieu65724892014-11-15 06:37:39 +000011109/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011110static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000011111 if (S.getLangOpts().Bool)
11112 return;
JF Bastiene77b48b2018-09-10 20:42:56 +000011113 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11114 return;
Richard Trieu65724892014-11-15 06:37:39 +000011115 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11116}
11117
John McCallcc7e5bf2010-05-06 08:58:33 +000011118/// AnalyzeImplicitConversions - Find and report any interesting
11119/// implicit conversions in the given expression. There are a couple
11120/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011121static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11122 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000011123 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000011124 Expr *E = OrigE->IgnoreParenImpCasts();
11125
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000011126 if (E->isTypeDependent() || E->isValueDependent())
11127 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011128
John McCallcc7e5bf2010-05-06 08:58:33 +000011129 // For conditional operators, we analyze the arguments as if they
11130 // were being fed directly into the output.
11131 if (isa<ConditionalOperator>(E)) {
11132 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000011133 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011134 return;
11135 }
11136
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011137 // Check implicit argument conversions for function calls.
11138 if (CallExpr *Call = dyn_cast<CallExpr>(E))
11139 CheckImplicitArgumentConversions(S, Call, CC);
11140
John McCallcc7e5bf2010-05-06 08:58:33 +000011141 // Go ahead and check any implicit conversions we might have skipped.
11142 // The non-canonical typecheck is just an optimization;
11143 // CheckImplicitConversion will filter out dead implicit conversions.
11144 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011145 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011146
11147 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000011148
11149 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11150 // The bound subexpressions in a PseudoObjectExpr are not reachable
11151 // as transitive children.
11152 // FIXME: Use a more uniform representation for this.
11153 for (auto *SE : POE->semantics())
11154 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11155 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000011156 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000011157
John McCallcc7e5bf2010-05-06 08:58:33 +000011158 // Skip past explicit casts.
JF Bastiene77b48b2018-09-10 20:42:56 +000011159 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11160 E = CE->getSubExpr()->IgnoreParenImpCasts();
11161 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11162 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCallacf0ee52010-10-08 02:01:28 +000011163 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011164 }
11165
John McCalld2a53122010-11-09 23:24:47 +000011166 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11167 // Do a somewhat different check with comparison operators.
11168 if (BO->isComparisonOp())
11169 return AnalyzeComparison(S, BO);
11170
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011171 // And with simple assignments.
11172 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000011173 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011174 // And with compound assignments.
11175 if (BO->isAssignmentOp())
11176 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000011177 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011178
11179 // These break the otherwise-useful invariant below. Fortunately,
11180 // we don't really need to recurse into them, because any internal
11181 // expressions should have been analyzed already when they were
11182 // built into statements.
11183 if (isa<StmtExpr>(E)) return;
11184
11185 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000011186 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000011187
11188 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000011189 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000011190 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000011191 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000011192 for (Stmt *SubStmt : E->children()) {
11193 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000011194 if (!ChildExpr)
11195 continue;
11196
Richard Trieu955231d2014-01-25 01:10:35 +000011197 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000011198 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000011199 // Ignore checking string literals that are in logical and operators.
11200 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000011201 continue;
11202 AnalyzeImplicitConversions(S, ChildExpr, CC);
11203 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011204
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011205 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000011206 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11207 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011208 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000011209
11210 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11211 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011212 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011213 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011214
JF Bastiene77b48b2018-09-10 20:42:56 +000011215 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11216 if (U->getOpcode() == UO_LNot) {
Richard Trieu65724892014-11-15 06:37:39 +000011217 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
JF Bastiene77b48b2018-09-10 20:42:56 +000011218 } else if (U->getOpcode() != UO_AddrOf) {
11219 if (U->getSubExpr()->getType()->isAtomicType())
11220 S.Diag(U->getSubExpr()->getBeginLoc(),
11221 diag::warn_atomic_implicit_seq_cst);
11222 }
11223 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011224}
11225
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011226/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011227static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11228 // Taking into account implicit conversions,
11229 // allow any integer.
11230 if (!E->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011231 S.Diag(E->getBeginLoc(),
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011232 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11233 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011234 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011235 // Potentially emit standard warnings for implicit conversions if enabled
11236 // using -Wconversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011237 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011238 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011239}
11240
Richard Trieuc1888e02014-06-28 23:25:37 +000011241// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11242// Returns true when emitting a warning about taking the address of a reference.
11243static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000011244 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000011245 E = E->IgnoreParenImpCasts();
11246
11247 const FunctionDecl *FD = nullptr;
11248
11249 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11250 if (!DRE->getDecl()->getType()->isReferenceType())
11251 return false;
11252 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11253 if (!M->getMemberDecl()->getType()->isReferenceType())
11254 return false;
11255 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000011256 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000011257 return false;
11258 FD = Call->getDirectCallee();
11259 } else {
11260 return false;
11261 }
11262
11263 SemaRef.Diag(E->getExprLoc(), PD);
11264
11265 // If possible, point to location of function.
11266 if (FD) {
11267 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11268 }
11269
11270 return true;
11271}
11272
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011273// Returns true if the SourceLocation is expanded from any macro body.
11274// Returns false if the SourceLocation is invalid, is from not in a macro
11275// expansion, or is from expanded from a top-level macro argument.
11276static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11277 if (Loc.isInvalid())
11278 return false;
11279
11280 while (Loc.isMacroID()) {
11281 if (SM.isMacroBodyExpansion(Loc))
11282 return true;
11283 Loc = SM.getImmediateMacroCallerLoc(Loc);
11284 }
11285
11286 return false;
11287}
11288
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011289/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000011290/// \param E the expression containing the pointer
11291/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11292/// compared to a null pointer
11293/// \param IsEqual True when the comparison is equal to a null pointer
11294/// \param Range Extra SourceRange to highlight in the diagnostic
11295void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11296 Expr::NullPointerConstantKind NullKind,
11297 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000011298 if (!E)
11299 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011300
11301 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011302 if (E->getExprLoc().isMacroID()) {
11303 const SourceManager &SM = getSourceManager();
11304 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11305 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000011306 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011307 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000011308 E = E->IgnoreImpCasts();
11309
11310 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11311
Richard Trieuf7432752014-06-06 21:39:26 +000011312 if (isa<CXXThisExpr>(E)) {
11313 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11314 : diag::warn_this_bool_conversion;
11315 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11316 return;
11317 }
11318
Richard Trieu3bb8b562014-02-26 02:36:06 +000011319 bool IsAddressOf = false;
11320
11321 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11322 if (UO->getOpcode() != UO_AddrOf)
11323 return;
11324 IsAddressOf = true;
11325 E = UO->getSubExpr();
11326 }
11327
Richard Trieuc1888e02014-06-28 23:25:37 +000011328 if (IsAddressOf) {
11329 unsigned DiagID = IsCompare
11330 ? diag::warn_address_of_reference_null_compare
11331 : diag::warn_address_of_reference_bool_conversion;
11332 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11333 << IsEqual;
11334 if (CheckForReference(*this, E, PD)) {
11335 return;
11336 }
11337 }
11338
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011339 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11340 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000011341 std::string Str;
11342 llvm::raw_string_ostream S(Str);
11343 E->printPretty(S, nullptr, getPrintingPolicy());
11344 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11345 : diag::warn_cast_nonnull_to_bool;
11346 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11347 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011348 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000011349 };
11350
11351 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11352 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11353 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011354 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11355 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011356 return;
11357 }
11358 }
11359 }
11360
Richard Trieu3bb8b562014-02-26 02:36:06 +000011361 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000011362 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011363 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11364 D = R->getDecl();
11365 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11366 D = M->getMemberDecl();
11367 }
11368
11369 // Weak Decls can be null.
11370 if (!D || D->isWeak())
11371 return;
George Burgess IV850269a2015-12-08 22:02:00 +000011372
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011373 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000011374 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11375 if (getCurFunction() &&
11376 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011377 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11378 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011379 return;
11380 }
11381
11382 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000011383 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000011384 assert(ParamIter != FD->param_end());
11385 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11386
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011387 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11388 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011389 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000011390 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011391 }
George Burgess IV850269a2015-12-08 22:02:00 +000011392
Joel E. Denny81508102018-03-13 14:51:22 +000011393 for (const ParamIdx &ArgNo : NonNull->args()) {
11394 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011395 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011396 return;
11397 }
George Burgess IV850269a2015-12-08 22:02:00 +000011398 }
11399 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011400 }
11401 }
George Burgess IV850269a2015-12-08 22:02:00 +000011402 }
11403
Richard Trieu3bb8b562014-02-26 02:36:06 +000011404 QualType T = D->getType();
11405 const bool IsArray = T->isArrayType();
11406 const bool IsFunction = T->isFunctionType();
11407
Richard Trieuc1888e02014-06-28 23:25:37 +000011408 // Address of function is used to silence the function warning.
11409 if (IsAddressOf && IsFunction) {
11410 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011411 }
11412
11413 // Found nothing.
11414 if (!IsAddressOf && !IsFunction && !IsArray)
11415 return;
11416
11417 // Pretty print the expression for the diagnostic.
11418 std::string Str;
11419 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000011420 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000011421
11422 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11423 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000011424 enum {
11425 AddressOf,
11426 FunctionPointer,
11427 ArrayPointer
11428 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011429 if (IsAddressOf)
11430 DiagType = AddressOf;
11431 else if (IsFunction)
11432 DiagType = FunctionPointer;
11433 else if (IsArray)
11434 DiagType = ArrayPointer;
11435 else
11436 llvm_unreachable("Could not determine diagnostic.");
11437 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11438 << Range << IsEqual;
11439
11440 if (!IsFunction)
11441 return;
11442
11443 // Suggest '&' to silence the function warning.
11444 Diag(E->getExprLoc(), diag::note_function_warning_silence)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011445 << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
Richard Trieu3bb8b562014-02-26 02:36:06 +000011446
11447 // Check to see if '()' fixit should be emitted.
11448 QualType ReturnType;
11449 UnresolvedSet<4> NonTemplateOverloads;
11450 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11451 if (ReturnType.isNull())
11452 return;
11453
11454 if (IsCompare) {
11455 // There are two cases here. If there is null constant, the only suggest
11456 // for a pointer return type. If the null is 0, then suggest if the return
11457 // type is a pointer or an integer type.
11458 if (!ReturnType->isPointerType()) {
11459 if (NullKind == Expr::NPCK_ZeroExpression ||
11460 NullKind == Expr::NPCK_ZeroLiteral) {
11461 if (!ReturnType->isIntegerType())
11462 return;
11463 } else {
11464 return;
11465 }
11466 }
11467 } else { // !IsCompare
11468 // For function to bool, only suggest if the function pointer has bool
11469 // return type.
11470 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11471 return;
11472 }
11473 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Kelly1c301dc2018-08-09 21:09:38 +000011474 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000011475}
11476
John McCallcc7e5bf2010-05-06 08:58:33 +000011477/// Diagnoses "dangerous" implicit conversions within the given
11478/// expression (which is a full expression). Implements -Wconversion
11479/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000011480///
11481/// \param CC the "context" location of the implicit conversion, i.e.
11482/// the most location of the syntactic entity requiring the implicit
11483/// conversion
11484void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011485 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000011486 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000011487 return;
11488
11489 // Don't diagnose for value- or type-dependent expressions.
11490 if (E->isTypeDependent() || E->isValueDependent())
11491 return;
11492
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011493 // Check for array bounds violations in cases where the check isn't triggered
11494 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11495 // ArraySubscriptExpr is on the RHS of a variable initialization.
11496 CheckArrayAccess(E);
11497
John McCallacf0ee52010-10-08 02:01:28 +000011498 // This is not the right CC for (e.g.) a variable initialization.
11499 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011500}
11501
Richard Trieu65724892014-11-15 06:37:39 +000011502/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11503/// Input argument E is a logical expression.
11504void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11505 ::CheckBoolLikeConversion(*this, E, CC);
11506}
11507
Richard Smith9f7df0c2017-06-26 23:19:32 +000011508/// Diagnose when expression is an integer constant expression and its evaluation
11509/// results in integer overflow
11510void Sema::CheckForIntOverflow (Expr *E) {
11511 // Use a work list to deal with nested struct initializers.
11512 SmallVector<Expr *, 2> Exprs(1, E);
11513
11514 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011515 Expr *OriginalE = Exprs.pop_back_val();
11516 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000011517
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011518 if (isa<BinaryOperator>(E)) {
11519 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000011520 continue;
11521 }
11522
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011523 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000011524 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011525 else if (isa<ObjCBoxedExpr>(OriginalE))
11526 E->EvaluateForOverflow(Context);
11527 else if (auto Call = dyn_cast<CallExpr>(E))
11528 Exprs.append(Call->arg_begin(), Call->arg_end());
11529 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11530 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000011531 } while (!Exprs.empty());
11532}
11533
Richard Smithc406cb72013-01-17 01:17:56 +000011534namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011535
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011536/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000011537/// same object.
11538class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011539 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000011540
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011541 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000011542 /// unsequenced if one is an ancestor or a descendent of the other. When we
11543 /// finish processing an expression with sequencing, such as a comma
11544 /// expression, we fold its tree nodes into its parent, since they are
11545 /// unsequenced with respect to nodes we will visit later.
11546 class SequenceTree {
11547 struct Value {
11548 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11549 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000011550 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000011551 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011552 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000011553
11554 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011555 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000011556 /// to some other region.
11557 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000011558 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011559
11560 unsigned Index = 0;
11561
11562 explicit Seq(unsigned N) : Index(N) {}
11563
Richard Smithc406cb72013-01-17 01:17:56 +000011564 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011565 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000011566 };
11567
11568 SequenceTree() { Values.push_back(Value(0)); }
11569 Seq root() const { return Seq(0); }
11570
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011571 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000011572 /// subset of \p Parent. This sequence of operations is sequenced with
11573 /// respect to other children of \p Parent.
11574 Seq allocate(Seq Parent) {
11575 Values.push_back(Value(Parent.Index));
11576 return Seq(Values.size() - 1);
11577 }
11578
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011579 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000011580 void merge(Seq S) {
11581 Values[S.Index].Merged = true;
11582 }
11583
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011584 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000011585 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11586 /// should have been merged into its parent as appropriate.
11587 bool isUnsequenced(Seq Cur, Seq Old) {
11588 unsigned C = representative(Cur.Index);
11589 unsigned Target = representative(Old.Index);
11590 while (C >= Target) {
11591 if (C == Target)
11592 return true;
11593 C = Values[C].Parent;
11594 }
11595 return false;
11596 }
11597
11598 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011599 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000011600 unsigned representative(unsigned K) {
11601 if (Values[K].Merged)
11602 // Perform path compression as we go.
11603 return Values[K].Parent = representative(Values[K].Parent);
11604 return K;
11605 }
11606 };
11607
11608 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011609 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000011610
11611 /// Different flavors of object usage which we track. We only track the
11612 /// least-sequenced usage of each kind.
11613 enum UsageKind {
11614 /// A read of an object. Multiple unsequenced reads are OK.
11615 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011616
Richard Smithc406cb72013-01-17 01:17:56 +000011617 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000011618 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000011619 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011620
Richard Smithc406cb72013-01-17 01:17:56 +000011621 /// A modification of an object which is not sequenced before the value
11622 /// computation of the expression, such as n++.
11623 UK_ModAsSideEffect,
11624
11625 UK_Count = UK_ModAsSideEffect + 1
11626 };
11627
11628 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011629 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011630 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011631
11632 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000011633 };
11634
11635 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000011636 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011637
Richard Smithc406cb72013-01-17 01:17:56 +000011638 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011639 bool Diagnosed = false;
11640
11641 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000011642 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011643 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000011644
11645 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011646
Richard Smithc406cb72013-01-17 01:17:56 +000011647 /// Sequenced regions within the expression.
11648 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011649
Richard Smithc406cb72013-01-17 01:17:56 +000011650 /// Declaration modifications and references which we have seen.
11651 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011652
Richard Smithc406cb72013-01-17 01:17:56 +000011653 /// The region we are currently within.
11654 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011655
Richard Smithc406cb72013-01-17 01:17:56 +000011656 /// Filled in with declarations which were modified as a side-effect
11657 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011658 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11659
Richard Smithd33f5202013-01-17 23:18:09 +000011660 /// Expressions to check later. We defer checking these to reduce
11661 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011662 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000011663
11664 /// RAII object wrapping the visitation of a sequenced subexpression of an
11665 /// expression. At the end of this process, the side-effects of the evaluation
11666 /// become sequenced with respect to the value computation of the result, so
11667 /// we downgrade any UK_ModAsSideEffect within the evaluation to
11668 /// UK_ModAsValue.
11669 struct SequencedSubexpression {
11670 SequencedSubexpression(SequenceChecker &Self)
11671 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11672 Self.ModAsSideEffect = &ModAsSideEffect;
11673 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011674
Richard Smithc406cb72013-01-17 01:17:56 +000011675 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000011676 for (auto &M : llvm::reverse(ModAsSideEffect)) {
11677 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000011678 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000011679 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11680 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000011681 }
11682 Self.ModAsSideEffect = OldModAsSideEffect;
11683 }
11684
11685 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011686 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011687 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000011688 };
11689
Richard Smith40238f02013-06-20 22:21:56 +000011690 /// RAII object wrapping the visitation of a subexpression which we might
11691 /// choose to evaluate as a constant. If any subexpression is evaluated and
11692 /// found to be non-constant, this allows us to suppress the evaluation of
11693 /// the outer expression.
11694 class EvaluationTracker {
11695 public:
11696 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011697 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000011698 Self.EvalTracker = this;
11699 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011700
Richard Smith40238f02013-06-20 22:21:56 +000011701 ~EvaluationTracker() {
11702 Self.EvalTracker = Prev;
11703 if (Prev)
11704 Prev->EvalOK &= EvalOK;
11705 }
11706
11707 bool evaluate(const Expr *E, bool &Result) {
11708 if (!EvalOK || E->isValueDependent())
11709 return false;
11710 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11711 return EvalOK;
11712 }
11713
11714 private:
11715 SequenceChecker &Self;
11716 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011717 bool EvalOK = true;
11718 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000011719
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011720 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000011721 /// if any.
11722 Object getObject(Expr *E, bool Mod) const {
11723 E = E->IgnoreParenCasts();
11724 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11725 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11726 return getObject(UO->getSubExpr(), Mod);
11727 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11728 if (BO->getOpcode() == BO_Comma)
11729 return getObject(BO->getRHS(), Mod);
11730 if (Mod && BO->isAssignmentOp())
11731 return getObject(BO->getLHS(), Mod);
11732 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11733 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11734 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11735 return ME->getMemberDecl();
11736 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11737 // FIXME: If this is a reference, map through to its value.
11738 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000011739 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011740 }
11741
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011742 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011743 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11744 Usage &U = UI.Uses[UK];
11745 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11746 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11747 ModAsSideEffect->push_back(std::make_pair(O, U));
11748 U.Use = Ref;
11749 U.Seq = Region;
11750 }
11751 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011753 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011754 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11755 bool IsModMod) {
11756 if (UI.Diagnosed)
11757 return;
11758
11759 const Usage &U = UI.Uses[OtherKind];
11760 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11761 return;
11762
11763 Expr *Mod = U.Use;
11764 Expr *ModOrUse = Ref;
11765 if (OtherKind == UK_Use)
11766 std::swap(Mod, ModOrUse);
11767
11768 SemaRef.Diag(Mod->getExprLoc(),
11769 IsModMod ? diag::warn_unsequenced_mod_mod
11770 : diag::warn_unsequenced_mod_use)
11771 << O << SourceRange(ModOrUse->getExprLoc());
11772 UI.Diagnosed = true;
11773 }
11774
11775 void notePreUse(Object O, Expr *Use) {
11776 UsageInfo &U = UsageMap[O];
11777 // Uses conflict with other modifications.
11778 checkUsage(O, U, Use, UK_ModAsValue, false);
11779 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011780
Richard Smithc406cb72013-01-17 01:17:56 +000011781 void notePostUse(Object O, Expr *Use) {
11782 UsageInfo &U = UsageMap[O];
11783 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11784 addUsage(U, O, Use, UK_Use);
11785 }
11786
11787 void notePreMod(Object O, Expr *Mod) {
11788 UsageInfo &U = UsageMap[O];
11789 // Modifications conflict with other modifications and with uses.
11790 checkUsage(O, U, Mod, UK_ModAsValue, true);
11791 checkUsage(O, U, Mod, UK_Use, false);
11792 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011793
Richard Smithc406cb72013-01-17 01:17:56 +000011794 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11795 UsageInfo &U = UsageMap[O];
11796 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11797 addUsage(U, O, Use, UK);
11798 }
11799
11800public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011801 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011802 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011803 Visit(E);
11804 }
11805
11806 void VisitStmt(Stmt *S) {
11807 // Skip all statements which aren't expressions for now.
11808 }
11809
11810 void VisitExpr(Expr *E) {
11811 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011812 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011813 }
11814
11815 void VisitCastExpr(CastExpr *E) {
11816 Object O = Object();
11817 if (E->getCastKind() == CK_LValueToRValue)
11818 O = getObject(E->getSubExpr(), false);
11819
11820 if (O)
11821 notePreUse(O, E);
11822 VisitExpr(E);
11823 if (O)
11824 notePostUse(O, E);
11825 }
11826
11827 void VisitBinComma(BinaryOperator *BO) {
11828 // C++11 [expr.comma]p1:
11829 // Every value computation and side effect associated with the left
11830 // expression is sequenced before every value computation and side
11831 // effect associated with the right expression.
11832 SequenceTree::Seq LHS = Tree.allocate(Region);
11833 SequenceTree::Seq RHS = Tree.allocate(Region);
11834 SequenceTree::Seq OldRegion = Region;
11835
11836 {
11837 SequencedSubexpression SeqLHS(*this);
11838 Region = LHS;
11839 Visit(BO->getLHS());
11840 }
11841
11842 Region = RHS;
11843 Visit(BO->getRHS());
11844
11845 Region = OldRegion;
11846
11847 // Forget that LHS and RHS are sequenced. They are both unsequenced
11848 // with respect to other stuff.
11849 Tree.merge(LHS);
11850 Tree.merge(RHS);
11851 }
11852
11853 void VisitBinAssign(BinaryOperator *BO) {
11854 // The modification is sequenced after the value computation of the LHS
11855 // and RHS, so check it before inspecting the operands and update the
11856 // map afterwards.
11857 Object O = getObject(BO->getLHS(), true);
11858 if (!O)
11859 return VisitExpr(BO);
11860
11861 notePreMod(O, BO);
11862
11863 // C++11 [expr.ass]p7:
11864 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11865 // only once.
11866 //
11867 // Therefore, for a compound assignment operator, O is considered used
11868 // everywhere except within the evaluation of E1 itself.
11869 if (isa<CompoundAssignOperator>(BO))
11870 notePreUse(O, BO);
11871
11872 Visit(BO->getLHS());
11873
11874 if (isa<CompoundAssignOperator>(BO))
11875 notePostUse(O, BO);
11876
11877 Visit(BO->getRHS());
11878
Richard Smith83e37bee2013-06-26 23:16:51 +000011879 // C++11 [expr.ass]p1:
11880 // the assignment is sequenced [...] before the value computation of the
11881 // assignment expression.
11882 // C11 6.5.16/3 has no such rule.
11883 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11884 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011885 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011886
Richard Smithc406cb72013-01-17 01:17:56 +000011887 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11888 VisitBinAssign(CAO);
11889 }
11890
11891 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11892 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11893 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11894 Object O = getObject(UO->getSubExpr(), true);
11895 if (!O)
11896 return VisitExpr(UO);
11897
11898 notePreMod(O, UO);
11899 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011900 // C++11 [expr.pre.incr]p1:
11901 // the expression ++x is equivalent to x+=1
11902 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11903 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011904 }
11905
11906 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11907 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11908 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11909 Object O = getObject(UO->getSubExpr(), true);
11910 if (!O)
11911 return VisitExpr(UO);
11912
11913 notePreMod(O, UO);
11914 Visit(UO->getSubExpr());
11915 notePostMod(O, UO, UK_ModAsSideEffect);
11916 }
11917
11918 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11919 void VisitBinLOr(BinaryOperator *BO) {
11920 // The side-effects of the LHS of an '&&' are sequenced before the
11921 // value computation of the RHS, and hence before the value computation
11922 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11923 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011924 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011925 {
11926 SequencedSubexpression Sequenced(*this);
11927 Visit(BO->getLHS());
11928 }
11929
11930 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011931 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011932 if (!Result)
11933 Visit(BO->getRHS());
11934 } else {
11935 // Check for unsequenced operations in the RHS, treating it as an
11936 // entirely separate evaluation.
11937 //
11938 // FIXME: If there are operations in the RHS which are unsequenced
11939 // with respect to operations outside the RHS, and those operations
11940 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011941 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011942 }
Richard Smithc406cb72013-01-17 01:17:56 +000011943 }
11944 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011945 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011946 {
11947 SequencedSubexpression Sequenced(*this);
11948 Visit(BO->getLHS());
11949 }
11950
11951 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011952 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011953 if (Result)
11954 Visit(BO->getRHS());
11955 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011956 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011957 }
Richard Smithc406cb72013-01-17 01:17:56 +000011958 }
11959
11960 // Only visit the condition, unless we can be sure which subexpression will
11961 // be chosen.
11962 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011963 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011964 {
11965 SequencedSubexpression Sequenced(*this);
11966 Visit(CO->getCond());
11967 }
Richard Smithc406cb72013-01-17 01:17:56 +000011968
11969 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011970 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011971 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011972 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011973 WorkList.push_back(CO->getTrueExpr());
11974 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011975 }
Richard Smithc406cb72013-01-17 01:17:56 +000011976 }
11977
Richard Smithe3dbfe02013-06-30 10:40:20 +000011978 void VisitCallExpr(CallExpr *CE) {
11979 // C++11 [intro.execution]p15:
11980 // When calling a function [...], every value computation and side effect
11981 // associated with any argument expression, or with the postfix expression
11982 // designating the called function, is sequenced before execution of every
11983 // expression or statement in the body of the function [and thus before
11984 // the value computation of its result].
11985 SequencedSubexpression Sequenced(*this);
11986 Base::VisitCallExpr(CE);
11987
11988 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11989 }
11990
Richard Smithc406cb72013-01-17 01:17:56 +000011991 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011992 // This is a call, so all subexpressions are sequenced before the result.
11993 SequencedSubexpression Sequenced(*this);
11994
Richard Smithc406cb72013-01-17 01:17:56 +000011995 if (!CCE->isListInitialization())
11996 return VisitExpr(CCE);
11997
11998 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011999 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012000 SequenceTree::Seq Parent = Region;
12001 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12002 E = CCE->arg_end();
12003 I != E; ++I) {
12004 Region = Tree.allocate(Parent);
12005 Elts.push_back(Region);
12006 Visit(*I);
12007 }
12008
12009 // Forget that the initializers are sequenced.
12010 Region = Parent;
12011 for (unsigned I = 0; I < Elts.size(); ++I)
12012 Tree.merge(Elts[I]);
12013 }
12014
12015 void VisitInitListExpr(InitListExpr *ILE) {
12016 if (!SemaRef.getLangOpts().CPlusPlus11)
12017 return VisitExpr(ILE);
12018
12019 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012020 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012021 SequenceTree::Seq Parent = Region;
12022 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12023 Expr *E = ILE->getInit(I);
12024 if (!E) continue;
12025 Region = Tree.allocate(Parent);
12026 Elts.push_back(Region);
12027 Visit(E);
12028 }
12029
12030 // Forget that the initializers are sequenced.
12031 Region = Parent;
12032 for (unsigned I = 0; I < Elts.size(); ++I)
12033 Tree.merge(Elts[I]);
12034 }
12035};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012036
12037} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000012038
12039void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012040 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000012041 WorkList.push_back(E);
12042 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000012043 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000012044 SequenceChecker(*this, Item, WorkList);
12045 }
Richard Smithc406cb72013-01-17 01:17:56 +000012046}
12047
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012048void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12049 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000012050 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000012051 if (!E->isInstantiationDependent())
12052 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012053 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000012054 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012055 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000012056}
12057
John McCall1f425642010-11-11 03:21:53 +000012058void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12059 FieldDecl *BitField,
12060 Expr *Init) {
12061 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12062}
12063
David Majnemer61a5bbf2015-04-07 22:08:51 +000012064static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12065 SourceLocation Loc) {
12066 if (!PType->isVariablyModifiedType())
12067 return;
12068 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12069 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12070 return;
12071 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000012072 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12073 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12074 return;
12075 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000012076 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12077 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12078 return;
12079 }
12080
12081 const ArrayType *AT = S.Context.getAsArrayType(PType);
12082 if (!AT)
12083 return;
12084
12085 if (AT->getSizeModifier() != ArrayType::Star) {
12086 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12087 return;
12088 }
12089
12090 S.Diag(Loc, diag::err_array_star_in_function_definition);
12091}
12092
Mike Stump0c2ec772010-01-21 03:59:47 +000012093/// CheckParmsForFunctionDef - Check that the parameters of the given
12094/// function are appropriate for the definition of a function. This
12095/// takes care of any checks that cannot be performed on the
12096/// declaration itself, e.g., that the types of each of the function
12097/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000012098bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000012099 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012100 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000012101 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012102 // C99 6.7.5.3p4: the parameters in a parameter type list in a
12103 // function declarator that is part of a function definition of
12104 // that function shall not have incomplete type.
12105 //
12106 // This is also C++ [dcl.fct]p6.
12107 if (!Param->isInvalidDecl() &&
12108 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012109 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012110 Param->setInvalidDecl();
12111 HasInvalidParm = true;
12112 }
12113
12114 // C99 6.9.1p5: If the declarator includes a parameter type list, the
12115 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000012116 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000012117 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000012118 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012119 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000012120 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000012121
12122 // C99 6.7.5.3p12:
12123 // If the function declarator is not part of a definition of that
12124 // function, parameters may have incomplete type and may use the [*]
12125 // notation in their sequences of declarator specifiers to specify
12126 // variable length array types.
12127 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000012128 // FIXME: This diagnostic should point the '[*]' if source-location
12129 // information is added for it.
12130 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012131
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012132 // If the parameter is a c++ class type and it has to be destructed in the
12133 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012134 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012135 if (!Param->isInvalidDecl()) {
12136 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12137 if (!ClassDecl->isInvalidDecl() &&
12138 !ClassDecl->hasIrrelevantDestructor() &&
12139 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000012140 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012141 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12142 MarkFunctionReferenced(Param->getLocation(), Destructor);
12143 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000012144 }
12145 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012146 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012147
12148 // Parameters with the pass_object_size attribute only need to be marked
12149 // constant at function definitions. Because we lack information about
12150 // whether we're on a declaration or definition when we're instantiating the
12151 // attribute, we need to check for constness here.
12152 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12153 if (!Param->getType().isConstQualified())
12154 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12155 << Attr->getSpelling() << 1;
Aaron Ballmanc3463f62018-12-05 18:56:57 +000012156
12157 // Check for parameter names shadowing fields from the class.
12158 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12159 // The owning context for the parameter should be the function, but we
12160 // want to see if this function's declaration context is a record.
12161 DeclContext *DC = Param->getDeclContext();
12162 if (DC && DC->isFunctionOrMethod()) {
12163 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12164 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12165 RD, /*DeclIsField*/ false);
12166 }
12167 }
Mike Stump0c2ec772010-01-21 03:59:47 +000012168 }
12169
12170 return HasInvalidParm;
12171}
John McCall2b5c1b22010-08-12 21:44:57 +000012172
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012173/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12174/// or MemberExpr.
12175static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12176 ASTContext &Context) {
12177 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12178 return Context.getDeclAlign(DRE->getDecl());
12179
12180 if (const auto *ME = dyn_cast<MemberExpr>(E))
12181 return Context.getDeclAlign(ME->getMemberDecl());
12182
12183 return TypeAlign;
12184}
12185
John McCall2b5c1b22010-08-12 21:44:57 +000012186/// CheckCastAlign - Implements -Wcast-align, which warns when a
12187/// pointer cast increases the alignment requirements.
12188void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12189 // This is actually a lot of work to potentially be doing on every
12190 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012191 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000012192 return;
12193
12194 // Ignore dependent types.
12195 if (T->isDependentType() || Op->getType()->isDependentType())
12196 return;
12197
12198 // Require that the destination be a pointer type.
12199 const PointerType *DestPtr = T->getAs<PointerType>();
12200 if (!DestPtr) return;
12201
12202 // If the destination has alignment 1, we're done.
12203 QualType DestPointee = DestPtr->getPointeeType();
12204 if (DestPointee->isIncompleteType()) return;
12205 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12206 if (DestAlign.isOne()) return;
12207
12208 // Require that the source be a pointer type.
12209 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12210 if (!SrcPtr) return;
12211 QualType SrcPointee = SrcPtr->getPointeeType();
12212
12213 // Whitelist casts from cv void*. We already implicitly
12214 // whitelisted casts to cv void*, since they have alignment 1.
12215 // Also whitelist casts involving incomplete types, which implicitly
12216 // includes 'void'.
12217 if (SrcPointee->isIncompleteType()) return;
12218
12219 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012220
12221 if (auto *CE = dyn_cast<CastExpr>(Op)) {
12222 if (CE->getCastKind() == CK_ArrayToPointerDecay)
12223 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12224 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12225 if (UO->getOpcode() == UO_AddrOf)
12226 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12227 }
12228
John McCall2b5c1b22010-08-12 21:44:57 +000012229 if (SrcAlign >= DestAlign) return;
12230
12231 Diag(TRange.getBegin(), diag::warn_cast_align)
12232 << Op->getType() << T
12233 << static_cast<unsigned>(SrcAlign.getQuantity())
12234 << static_cast<unsigned>(DestAlign.getQuantity())
12235 << TRange << Op->getSourceRange();
12236}
12237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012238/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000012239/// array member of a struct.
12240///
12241/// We avoid emitting out-of-bounds access warnings for such arrays as they are
12242/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000012243static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000012244 const NamedDecl *ND) {
12245 if (Size != 1 || !ND) return false;
12246
12247 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12248 if (!FD) return false;
12249
12250 // Don't consider sizes resulting from macro expansions or template argument
12251 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000012252
12253 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012254 while (TInfo) {
12255 TypeLoc TL = TInfo->getTypeLoc();
12256 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000012257 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12258 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012259 TInfo = TDL->getTypeSourceInfo();
12260 continue;
12261 }
David Blaikie6adc78e2013-02-18 22:06:02 +000012262 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12263 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000012264 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12265 return false;
12266 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012267 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000012268 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012269
12270 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000012271 if (!RD) return false;
12272 if (RD->isUnion()) return false;
12273 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12274 if (!CRD->isStandardLayout()) return false;
12275 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012276
Benjamin Kramer8c543672011-08-06 03:04:42 +000012277 // See if this is the last field decl in the record.
12278 const Decl *D = FD;
12279 while ((D = D->getNextDeclInContext()))
12280 if (isa<FieldDecl>(D))
12281 return false;
12282 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000012283}
12284
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012285void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012286 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000012287 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012288 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012289 if (IndexExpr->isValueDependent())
12290 return;
12291
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000012292 const Type *EffectiveType =
12293 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012294 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012295 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012296 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012297 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000012298 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000012299
Fangrui Song407659a2018-11-30 23:41:18 +000012300 Expr::EvalResult Result;
12301 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000012302 return;
Fangrui Song407659a2018-11-30 23:41:18 +000012303
12304 llvm::APSInt index = Result.Val.getInt();
Richard Smith13f67182011-12-16 19:31:14 +000012305 if (IndexNegated)
12306 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000012307
Craig Topperc3ec1492014-05-26 06:22:03 +000012308 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000012309 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012310 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000012311 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012312 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000012313
Ted Kremeneke4b316c2011-02-23 23:06:04 +000012314 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012315 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000012316 if (!size.isStrictlyPositive())
12317 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012318
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000012319 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000012320 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012321 // Make sure we're comparing apples to apples when comparing index to size
12322 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12323 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000012324 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000012325 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012326 if (ptrarith_typesize != array_typesize) {
12327 // There's a cast to a different size type involved
12328 uint64_t ratio = array_typesize / ptrarith_typesize;
12329 // TODO: Be smarter about handling cases where array_typesize is not a
12330 // multiple of ptrarith_typesize
12331 if (ptrarith_typesize * ratio == array_typesize)
12332 size *= llvm::APInt(size.getBitWidth(), ratio);
12333 }
12334 }
12335
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012336 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012337 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012338 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012339 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012340
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012341 // For array subscripting the index must be less than size, but for pointer
12342 // arithmetic also allow the index (offset) to be equal to size since
12343 // computing the next address after the end of the array is legal and
12344 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012345 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000012346 return;
12347
12348 // Also don't warn for arrays of size 1 which are members of some
12349 // structure. These are often used to approximate flexible arrays in C89
12350 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012351 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000012352 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012353
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012354 // Suppress the warning if the subscript expression (as identified by the
12355 // ']' location) and the index expression are both from macro expansions
12356 // within a system header.
12357 if (ASE) {
12358 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12359 ASE->getRBracketLoc());
12360 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012361 SourceLocation IndexLoc =
12362 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
Eli Friedman5ba37d52013-08-22 00:27:10 +000012363 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012364 return;
12365 }
12366 }
12367
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012368 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012369 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012370 DiagID = diag::warn_array_index_exceeds_bounds;
12371
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012372 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012373 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012374 << size.toString(10, true)
12375 << (unsigned)size.getLimitedValue(~0U)
12376 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012377 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012378 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012379 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012380 DiagID = diag::warn_ptr_arith_precedes_bounds;
12381 if (index.isNegative()) index = -index;
12382 }
12383
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012384 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012385 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012386 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000012387 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000012388
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012389 if (!ND) {
12390 // Try harder to find a NamedDecl to point at in the note.
12391 while (const ArraySubscriptExpr *ASE =
12392 dyn_cast<ArraySubscriptExpr>(BaseExpr))
12393 BaseExpr = ASE->getBase()->IgnoreParenCasts();
12394 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012395 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012396 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012397 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012398 }
12399
Chandler Carruth1af88f12011-02-17 21:10:52 +000012400 if (ND)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012401 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012402 PDiag(diag::note_array_index_out_of_bounds)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012403 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000012404}
12405
Ted Kremenekdf26df72011-03-01 18:41:00 +000012406void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012407 int AllowOnePastEnd = 0;
12408 while (expr) {
12409 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000012410 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012411 case Stmt::ArraySubscriptExprClass: {
12412 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012413 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012414 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000012415 expr = ASE->getBase();
12416 break;
12417 }
12418 case Stmt::MemberExprClass: {
12419 expr = cast<MemberExpr>(expr)->getBase();
12420 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012421 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012422 case Stmt::OMPArraySectionExprClass: {
12423 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12424 if (ASE->getLowerBound())
12425 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12426 /*ASE=*/nullptr, AllowOnePastEnd > 0);
12427 return;
12428 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012429 case Stmt::UnaryOperatorClass: {
12430 // Only unwrap the * and & unary operators
12431 const UnaryOperator *UO = cast<UnaryOperator>(expr);
12432 expr = UO->getSubExpr();
12433 switch (UO->getOpcode()) {
12434 case UO_AddrOf:
12435 AllowOnePastEnd++;
12436 break;
12437 case UO_Deref:
12438 AllowOnePastEnd--;
12439 break;
12440 default:
12441 return;
12442 }
12443 break;
12444 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012445 case Stmt::ConditionalOperatorClass: {
12446 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12447 if (const Expr *lhs = cond->getLHS())
12448 CheckArrayAccess(lhs);
12449 if (const Expr *rhs = cond->getRHS())
12450 CheckArrayAccess(rhs);
12451 return;
12452 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000012453 case Stmt::CXXOperatorCallExprClass: {
12454 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12455 for (const auto *Arg : OCE->arguments())
12456 CheckArrayAccess(Arg);
12457 return;
12458 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012459 default:
12460 return;
12461 }
Peter Collingbourne91147592011-04-15 00:35:48 +000012462 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012463}
John McCall31168b02011-06-15 23:02:42 +000012464
12465//===--- CHECK: Objective-C retain cycles ----------------------------------//
12466
12467namespace {
John McCall31168b02011-06-15 23:02:42 +000012468
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012469struct RetainCycleOwner {
12470 VarDecl *Variable = nullptr;
12471 SourceRange Range;
12472 SourceLocation Loc;
12473 bool Indirect = false;
12474
12475 RetainCycleOwner() = default;
12476
12477 void setLocsFrom(Expr *e) {
12478 Loc = e->getExprLoc();
12479 Range = e->getSourceRange();
12480 }
12481};
12482
12483} // namespace
John McCall31168b02011-06-15 23:02:42 +000012484
12485/// Consider whether capturing the given variable can possibly lead to
12486/// a retain cycle.
12487static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000012488 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000012489 // lifetime. In MRR, it's captured strongly if the variable is
12490 // __block and has an appropriate type.
12491 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12492 return false;
12493
12494 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012495 if (ref)
12496 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000012497 return true;
12498}
12499
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012500static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000012501 while (true) {
12502 e = e->IgnoreParens();
12503 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12504 switch (cast->getCastKind()) {
12505 case CK_BitCast:
12506 case CK_LValueBitCast:
12507 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000012508 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000012509 e = cast->getSubExpr();
12510 continue;
12511
John McCall31168b02011-06-15 23:02:42 +000012512 default:
12513 return false;
12514 }
12515 }
12516
12517 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12518 ObjCIvarDecl *ivar = ref->getDecl();
12519 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12520 return false;
12521
12522 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012523 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000012524 return false;
12525
12526 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12527 owner.Indirect = true;
12528 return true;
12529 }
12530
12531 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12532 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12533 if (!var) return false;
12534 return considerVariable(var, ref, owner);
12535 }
12536
John McCall31168b02011-06-15 23:02:42 +000012537 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12538 if (member->isArrow()) return false;
12539
12540 // Don't count this as an indirect ownership.
12541 e = member->getBase();
12542 continue;
12543 }
12544
John McCallfe96e0b2011-11-06 09:01:30 +000012545 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12546 // Only pay attention to pseudo-objects on property references.
12547 ObjCPropertyRefExpr *pre
12548 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12549 ->IgnoreParens());
12550 if (!pre) return false;
12551 if (pre->isImplicitProperty()) return false;
12552 ObjCPropertyDecl *property = pre->getExplicitProperty();
12553 if (!property->isRetaining() &&
12554 !(property->getPropertyIvarDecl() &&
12555 property->getPropertyIvarDecl()->getType()
12556 .getObjCLifetime() == Qualifiers::OCL_Strong))
12557 return false;
12558
12559 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012560 if (pre->isSuperReceiver()) {
12561 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12562 if (!owner.Variable)
12563 return false;
12564 owner.Loc = pre->getLocation();
12565 owner.Range = pre->getSourceRange();
12566 return true;
12567 }
John McCallfe96e0b2011-11-06 09:01:30 +000012568 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12569 ->getSourceExpr());
12570 continue;
12571 }
12572
John McCall31168b02011-06-15 23:02:42 +000012573 // Array ivars?
12574
12575 return false;
12576 }
12577}
12578
12579namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012580
John McCall31168b02011-06-15 23:02:42 +000012581 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012582 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000012583 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012584 Expr *Capturer = nullptr;
12585 bool VarWillBeReased = false;
12586
12587 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12588 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12589 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000012590
12591 void VisitDeclRefExpr(DeclRefExpr *ref) {
12592 if (ref->getDecl() == Variable && !Capturer)
12593 Capturer = ref;
12594 }
12595
John McCall31168b02011-06-15 23:02:42 +000012596 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12597 if (Capturer) return;
12598 Visit(ref->getBase());
12599 if (Capturer && ref->isFreeIvar())
12600 Capturer = ref;
12601 }
12602
12603 void VisitBlockExpr(BlockExpr *block) {
Fangrui Song6907ce22018-07-30 19:24:48 +000012604 // Look inside nested blocks
John McCall31168b02011-06-15 23:02:42 +000012605 if (block->getBlockDecl()->capturesVariable(Variable))
12606 Visit(block->getBlockDecl()->getBody());
12607 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012608
Fariborz Jahanian0e337542012-08-31 20:04:47 +000012609 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12610 if (Capturer) return;
12611 if (OVE->getSourceExpr())
12612 Visit(OVE->getSourceExpr());
12613 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012614
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012615 void VisitBinaryOperator(BinaryOperator *BinOp) {
12616 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12617 return;
12618 Expr *LHS = BinOp->getLHS();
12619 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12620 if (DRE->getDecl() != Variable)
12621 return;
12622 if (Expr *RHS = BinOp->getRHS()) {
12623 RHS = RHS->IgnoreParenCasts();
12624 llvm::APSInt Value;
12625 VarWillBeReased =
12626 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12627 }
12628 }
12629 }
John McCall31168b02011-06-15 23:02:42 +000012630 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012631
12632} // namespace
John McCall31168b02011-06-15 23:02:42 +000012633
12634/// Check whether the given argument is a block which captures a
12635/// variable.
12636static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12637 assert(owner.Variable && owner.Loc.isValid());
12638
12639 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000012640
12641 // Look through [^{...} copy] and Block_copy(^{...}).
12642 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12643 Selector Cmd = ME->getSelector();
12644 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12645 e = ME->getInstanceReceiver();
12646 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000012647 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000012648 e = e->IgnoreParenCasts();
12649 }
12650 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12651 if (CE->getNumArgs() == 1) {
12652 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000012653 if (Fn) {
12654 const IdentifierInfo *FnI = Fn->getIdentifier();
12655 if (FnI && FnI->isStr("_Block_copy")) {
12656 e = CE->getArg(0)->IgnoreParenCasts();
12657 }
12658 }
Jordan Rose67e887c2012-09-17 17:54:30 +000012659 }
12660 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012661
John McCall31168b02011-06-15 23:02:42 +000012662 BlockExpr *block = dyn_cast<BlockExpr>(e);
12663 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000012664 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000012665
12666 FindCaptureVisitor visitor(S.Context, owner.Variable);
12667 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012668 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000012669}
12670
12671static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12672 RetainCycleOwner &owner) {
12673 assert(capturer);
12674 assert(owner.Variable && owner.Loc.isValid());
12675
12676 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12677 << owner.Variable << capturer->getSourceRange();
12678 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12679 << owner.Indirect << owner.Range;
12680}
12681
12682/// Check for a keyword selector that starts with the word 'add' or
12683/// 'set'.
12684static bool isSetterLikeSelector(Selector sel) {
12685 if (sel.isUnarySelector()) return false;
12686
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012687 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000012688 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012689 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000012690 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012691 else if (str.startswith("add")) {
12692 // Specially whitelist 'addOperationWithBlock:'.
12693 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12694 return false;
12695 str = str.substr(3);
12696 }
John McCall31168b02011-06-15 23:02:42 +000012697 else
12698 return false;
12699
12700 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000012701 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000012702}
12703
Benjamin Kramer3a743452015-03-09 15:03:32 +000012704static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12705 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012706 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12707 Message->getReceiverInterface(),
12708 NSAPI::ClassId_NSMutableArray);
12709 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012710 return None;
12711 }
12712
12713 Selector Sel = Message->getSelector();
12714
12715 Optional<NSAPI::NSArrayMethodKind> MKOpt =
12716 S.NSAPIObj->getNSArrayMethodKind(Sel);
12717 if (!MKOpt) {
12718 return None;
12719 }
12720
12721 NSAPI::NSArrayMethodKind MK = *MKOpt;
12722
12723 switch (MK) {
12724 case NSAPI::NSMutableArr_addObject:
12725 case NSAPI::NSMutableArr_insertObjectAtIndex:
12726 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12727 return 0;
12728 case NSAPI::NSMutableArr_replaceObjectAtIndex:
12729 return 1;
12730
12731 default:
12732 return None;
12733 }
12734
12735 return None;
12736}
12737
12738static
12739Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12740 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012741 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12742 Message->getReceiverInterface(),
12743 NSAPI::ClassId_NSMutableDictionary);
12744 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012745 return None;
12746 }
12747
12748 Selector Sel = Message->getSelector();
12749
12750 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12751 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12752 if (!MKOpt) {
12753 return None;
12754 }
12755
12756 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12757
12758 switch (MK) {
12759 case NSAPI::NSMutableDict_setObjectForKey:
12760 case NSAPI::NSMutableDict_setValueForKey:
12761 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12762 return 0;
12763
12764 default:
12765 return None;
12766 }
12767
12768 return None;
12769}
12770
12771static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012772 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12773 Message->getReceiverInterface(),
12774 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012775
Alex Denisov5dfac812015-08-06 04:51:14 +000012776 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12777 Message->getReceiverInterface(),
12778 NSAPI::ClassId_NSMutableOrderedSet);
12779 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012780 return None;
12781 }
12782
12783 Selector Sel = Message->getSelector();
12784
12785 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12786 if (!MKOpt) {
12787 return None;
12788 }
12789
12790 NSAPI::NSSetMethodKind MK = *MKOpt;
12791
12792 switch (MK) {
12793 case NSAPI::NSMutableSet_addObject:
12794 case NSAPI::NSOrderedSet_setObjectAtIndex:
12795 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12796 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12797 return 0;
12798 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12799 return 1;
12800 }
12801
12802 return None;
12803}
12804
12805void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12806 if (!Message->isInstanceMessage()) {
12807 return;
12808 }
12809
12810 Optional<int> ArgOpt;
12811
12812 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12813 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12814 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12815 return;
12816 }
12817
12818 int ArgIndex = *ArgOpt;
12819
Alex Denisove1d882c2015-03-04 17:55:52 +000012820 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12821 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12822 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12823 }
12824
Alex Denisov5dfac812015-08-06 04:51:14 +000012825 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012826 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012827 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012828 Diag(Message->getSourceRange().getBegin(),
12829 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012830 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012831 }
12832 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012833 } else {
12834 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12835
12836 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12837 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12838 }
12839
12840 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12841 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12842 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12843 ValueDecl *Decl = ReceiverRE->getDecl();
12844 Diag(Message->getSourceRange().getBegin(),
12845 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012846 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012847 if (!ArgRE->isObjCSelfExpr()) {
12848 Diag(Decl->getLocation(),
12849 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012850 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012851 }
12852 }
12853 }
12854 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12855 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12856 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12857 ObjCIvarDecl *Decl = IvarRE->getDecl();
12858 Diag(Message->getSourceRange().getBegin(),
12859 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012860 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012861 Diag(Decl->getLocation(),
12862 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012863 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012864 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012865 }
12866 }
12867 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012868}
12869
John McCall31168b02011-06-15 23:02:42 +000012870/// Check a message send to see if it's likely to cause a retain cycle.
12871void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12872 // Only check instance methods whose selector looks like a setter.
12873 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12874 return;
12875
12876 // Try to find a variable that the receiver is strongly owned by.
12877 RetainCycleOwner owner;
12878 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012879 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012880 return;
12881 } else {
12882 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12883 owner.Variable = getCurMethodDecl()->getSelfDecl();
12884 owner.Loc = msg->getSuperLoc();
12885 owner.Range = msg->getSuperLoc();
12886 }
12887
12888 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012889 const ObjCMethodDecl *MD = msg->getMethodDecl();
12890 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12891 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12892 // noescape blocks should not be retained by the method.
12893 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12894 continue;
John McCall31168b02011-06-15 23:02:42 +000012895 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012896 }
12897 }
John McCall31168b02011-06-15 23:02:42 +000012898}
12899
12900/// Check a property assign to see if it's likely to cause a retain cycle.
12901void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12902 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012903 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012904 return;
12905
12906 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12907 diagnoseRetainCycle(*this, capturer, owner);
12908}
12909
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012910void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12911 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012912 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012913 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000012914
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012915 // Because we don't have an expression for the variable, we have to set the
12916 // location explicitly here.
12917 Owner.Loc = Var->getLocation();
12918 Owner.Range = Var->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +000012919
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012920 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12921 diagnoseRetainCycle(*this, Capturer, Owner);
12922}
12923
Ted Kremenek9304da92012-12-21 08:04:28 +000012924static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12925 Expr *RHS, bool isProperty) {
12926 // Check if RHS is an Objective-C object literal, which also can get
12927 // immediately zapped in a weak reference. Note that we explicitly
12928 // allow ObjCStringLiterals, since those are designed to never really die.
12929 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012930
Ted Kremenek64873352012-12-21 22:46:35 +000012931 // This enum needs to match with the 'select' in
12932 // warn_objc_arc_literal_assign (off-by-1).
12933 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12934 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12935 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012936
12937 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012938 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012939 << (isProperty ? 0 : 1)
12940 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012941
12942 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012943}
12944
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012945static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12946 Qualifiers::ObjCLifetime LT,
12947 Expr *RHS, bool isProperty) {
12948 // Strip off any implicit cast added to get to the one ARC-specific.
12949 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12950 if (cast->getCastKind() == CK_ARCConsumeObject) {
12951 S.Diag(Loc, diag::warn_arc_retained_assign)
12952 << (LT == Qualifiers::OCL_ExplicitNone)
12953 << (isProperty ? 0 : 1)
12954 << RHS->getSourceRange();
12955 return true;
12956 }
12957 RHS = cast->getSubExpr();
12958 }
12959
12960 if (LT == Qualifiers::OCL_Weak &&
12961 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12962 return true;
12963
12964 return false;
12965}
12966
Ted Kremenekb36234d2012-12-21 08:04:20 +000012967bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12968 QualType LHS, Expr *RHS) {
12969 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12970
12971 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12972 return false;
12973
12974 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12975 return true;
12976
12977 return false;
12978}
12979
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012980void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12981 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012982 QualType LHSType;
12983 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012984 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012985 ObjCPropertyRefExpr *PRE
12986 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12987 if (PRE && !PRE->isImplicitProperty()) {
12988 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12989 if (PD)
12990 LHSType = PD->getType();
12991 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012992
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012993 if (LHSType.isNull())
12994 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012995
12996 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12997
12998 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012999 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000013000 getCurFunction()->markSafeWeakUse(LHS);
13001 }
13002
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013003 if (checkUnsafeAssigns(Loc, LHSType, RHS))
13004 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000013005
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013006 // FIXME. Check for other life times.
13007 if (LT != Qualifiers::OCL_None)
13008 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013009
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013010 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013011 if (PRE->isImplicitProperty())
13012 return;
13013 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13014 if (!PD)
13015 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013016
Bill Wendling44426052012-12-20 19:22:21 +000013017 unsigned Attributes = PD->getPropertyAttributes();
13018 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013019 // when 'assign' attribute was not explicitly specified
13020 // by user, ignore it and rely on property type itself
13021 // for lifetime info.
13022 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13023 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13024 LHSType->isObjCRetainableType())
13025 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013026
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013027 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000013028 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013029 Diag(Loc, diag::warn_arc_retained_property_assign)
13030 << RHS->getSourceRange();
13031 return;
13032 }
13033 RHS = cast->getSubExpr();
13034 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013035 }
Bill Wendling44426052012-12-20 19:22:21 +000013036 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000013037 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13038 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000013039 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013040 }
13041}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013042
13043//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13044
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013045static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13046 SourceLocation StmtLoc,
13047 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013048 // Do not warn if the body is a macro that expands to nothing, e.g:
13049 //
13050 // #define CALL(x)
13051 // if (condition)
13052 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013053 if (Body->hasLeadingEmptyMacro())
13054 return false;
13055
13056 // Get line numbers of statement and body.
13057 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000013058 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013059 &StmtLineInvalid);
13060 if (StmtLineInvalid)
13061 return false;
13062
13063 bool BodyLineInvalid;
13064 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13065 &BodyLineInvalid);
13066 if (BodyLineInvalid)
13067 return false;
13068
13069 // Warn if null statement and body are on the same line.
13070 if (StmtLine != BodyLine)
13071 return false;
13072
13073 return true;
13074}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013075
13076void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13077 const Stmt *Body,
13078 unsigned DiagID) {
13079 // Since this is a syntactic check, don't emit diagnostic for template
13080 // instantiations, this just adds noise.
13081 if (CurrentInstantiationScope)
13082 return;
13083
13084 // The body should be a null statement.
13085 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13086 if (!NBody)
13087 return;
13088
13089 // Do the usual checks.
13090 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13091 return;
13092
13093 Diag(NBody->getSemiLoc(), DiagID);
13094 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13095}
13096
13097void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13098 const Stmt *PossibleBody) {
13099 assert(!CurrentInstantiationScope); // Ensured by caller
13100
13101 SourceLocation StmtLoc;
13102 const Stmt *Body;
13103 unsigned DiagID;
13104 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13105 StmtLoc = FS->getRParenLoc();
13106 Body = FS->getBody();
13107 DiagID = diag::warn_empty_for_body;
13108 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13109 StmtLoc = WS->getCond()->getSourceRange().getEnd();
13110 Body = WS->getBody();
13111 DiagID = diag::warn_empty_while_body;
13112 } else
13113 return; // Neither `for' nor `while'.
13114
13115 // The body should be a null statement.
13116 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13117 if (!NBody)
13118 return;
13119
13120 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013121 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013122 return;
13123
13124 // Do the usual checks.
13125 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13126 return;
13127
13128 // `for(...);' and `while(...);' are popular idioms, so in order to keep
13129 // noise level low, emit diagnostics only if for/while is followed by a
13130 // CompoundStmt, e.g.:
13131 // for (int i = 0; i < n; i++);
13132 // {
13133 // a(i);
13134 // }
13135 // or if for/while is followed by a statement with more indentation
13136 // than for/while itself:
13137 // for (int i = 0; i < n; i++);
13138 // a(i);
13139 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13140 if (!ProbableTypo) {
13141 bool BodyColInvalid;
13142 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013143 PossibleBody->getBeginLoc(), &BodyColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013144 if (BodyColInvalid)
13145 return;
13146
13147 bool StmtColInvalid;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013148 unsigned StmtCol =
13149 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013150 if (StmtColInvalid)
13151 return;
13152
13153 if (BodyCol > StmtCol)
13154 ProbableTypo = true;
13155 }
13156
13157 if (ProbableTypo) {
13158 Diag(NBody->getSemiLoc(), DiagID);
13159 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13160 }
13161}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013162
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013163//===--- CHECK: Warn on self move with std::move. -------------------------===//
13164
13165/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13166void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13167 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013168 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13169 return;
13170
Richard Smith51ec0cf2017-02-21 01:17:38 +000013171 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013172 return;
13173
13174 // Strip parens and casts away.
13175 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13176 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13177
13178 // Check for a call expression
13179 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13180 if (!CE || CE->getNumArgs() != 1)
13181 return;
13182
13183 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000013184 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013185 return;
13186
13187 // Get argument from std::move
13188 RHSExpr = CE->getArg(0);
13189
13190 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13191 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13192
13193 // Two DeclRefExpr's, check that the decls are the same.
13194 if (LHSDeclRef && RHSDeclRef) {
13195 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13196 return;
13197 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13198 RHSDeclRef->getDecl()->getCanonicalDecl())
13199 return;
13200
13201 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13202 << LHSExpr->getSourceRange()
13203 << RHSExpr->getSourceRange();
13204 return;
13205 }
13206
13207 // Member variables require a different approach to check for self moves.
13208 // MemberExpr's are the same if every nested MemberExpr refers to the same
13209 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13210 // the base Expr's are CXXThisExpr's.
13211 const Expr *LHSBase = LHSExpr;
13212 const Expr *RHSBase = RHSExpr;
13213 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13214 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13215 if (!LHSME || !RHSME)
13216 return;
13217
13218 while (LHSME && RHSME) {
13219 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13220 RHSME->getMemberDecl()->getCanonicalDecl())
13221 return;
13222
13223 LHSBase = LHSME->getBase();
13224 RHSBase = RHSME->getBase();
13225 LHSME = dyn_cast<MemberExpr>(LHSBase);
13226 RHSME = dyn_cast<MemberExpr>(RHSBase);
13227 }
13228
13229 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13230 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13231 if (LHSDeclRef && RHSDeclRef) {
13232 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13233 return;
13234 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13235 RHSDeclRef->getDecl()->getCanonicalDecl())
13236 return;
13237
13238 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13239 << LHSExpr->getSourceRange()
13240 << RHSExpr->getSourceRange();
13241 return;
13242 }
13243
13244 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13245 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13246 << LHSExpr->getSourceRange()
13247 << RHSExpr->getSourceRange();
13248}
13249
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013250//===--- Layout compatibility ----------------------------------------------//
13251
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013252static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013253
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013254/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013255static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013256 // C++11 [dcl.enum] p8:
13257 // Two enumeration types are layout-compatible if they have the same
13258 // underlying type.
13259 return ED1->isComplete() && ED2->isComplete() &&
13260 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13261}
13262
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013263/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013264static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13265 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013266 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13267 return false;
13268
13269 if (Field1->isBitField() != Field2->isBitField())
13270 return false;
13271
13272 if (Field1->isBitField()) {
13273 // Make sure that the bit-fields are the same length.
13274 unsigned Bits1 = Field1->getBitWidthValue(C);
13275 unsigned Bits2 = Field2->getBitWidthValue(C);
13276
13277 if (Bits1 != Bits2)
13278 return false;
13279 }
13280
13281 return true;
13282}
13283
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013284/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013285/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013286static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13287 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013288 // If both records are C++ classes, check that base classes match.
13289 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13290 // If one of records is a CXXRecordDecl we are in C++ mode,
13291 // thus the other one is a CXXRecordDecl, too.
13292 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13293 // Check number of base classes.
13294 if (D1CXX->getNumBases() != D2CXX->getNumBases())
13295 return false;
13296
13297 // Check the base classes.
13298 for (CXXRecordDecl::base_class_const_iterator
13299 Base1 = D1CXX->bases_begin(),
13300 BaseEnd1 = D1CXX->bases_end(),
13301 Base2 = D2CXX->bases_begin();
13302 Base1 != BaseEnd1;
13303 ++Base1, ++Base2) {
13304 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13305 return false;
13306 }
13307 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13308 // If only RD2 is a C++ class, it should have zero base classes.
13309 if (D2CXX->getNumBases() > 0)
13310 return false;
13311 }
13312
13313 // Check the fields.
13314 RecordDecl::field_iterator Field2 = RD2->field_begin(),
13315 Field2End = RD2->field_end(),
13316 Field1 = RD1->field_begin(),
13317 Field1End = RD1->field_end();
13318 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13319 if (!isLayoutCompatible(C, *Field1, *Field2))
13320 return false;
13321 }
13322 if (Field1 != Field1End || Field2 != Field2End)
13323 return false;
13324
13325 return true;
13326}
13327
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013328/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013329/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013330static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13331 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013332 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013333 for (auto *Field2 : RD2->fields())
13334 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013335
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013336 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013337 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13338 I = UnmatchedFields.begin(),
13339 E = UnmatchedFields.end();
13340
13341 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013342 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013343 bool Result = UnmatchedFields.erase(*I);
13344 (void) Result;
13345 assert(Result);
13346 break;
13347 }
13348 }
13349 if (I == E)
13350 return false;
13351 }
13352
13353 return UnmatchedFields.empty();
13354}
13355
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013356static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13357 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013358 if (RD1->isUnion() != RD2->isUnion())
13359 return false;
13360
13361 if (RD1->isUnion())
13362 return isLayoutCompatibleUnion(C, RD1, RD2);
13363 else
13364 return isLayoutCompatibleStruct(C, RD1, RD2);
13365}
13366
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013367/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013368static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013369 if (T1.isNull() || T2.isNull())
13370 return false;
13371
13372 // C++11 [basic.types] p11:
13373 // If two types T1 and T2 are the same type, then T1 and T2 are
13374 // layout-compatible types.
13375 if (C.hasSameType(T1, T2))
13376 return true;
13377
13378 T1 = T1.getCanonicalType().getUnqualifiedType();
13379 T2 = T2.getCanonicalType().getUnqualifiedType();
13380
13381 const Type::TypeClass TC1 = T1->getTypeClass();
13382 const Type::TypeClass TC2 = T2->getTypeClass();
13383
13384 if (TC1 != TC2)
13385 return false;
13386
13387 if (TC1 == Type::Enum) {
13388 return isLayoutCompatible(C,
13389 cast<EnumType>(T1)->getDecl(),
13390 cast<EnumType>(T2)->getDecl());
13391 } else if (TC1 == Type::Record) {
13392 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13393 return false;
13394
13395 return isLayoutCompatible(C,
13396 cast<RecordType>(T1)->getDecl(),
13397 cast<RecordType>(T2)->getDecl());
13398 }
13399
13400 return false;
13401}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013402
13403//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13404
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013405/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013406///
13407/// \param TypeExpr Type tag expression, as it appears in user's code.
13408///
13409/// \param VD Declaration of an identifier that appears in a type tag.
13410///
13411/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013412static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13413 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013414 while(true) {
13415 if (!TypeExpr)
13416 return false;
13417
13418 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13419
13420 switch (TypeExpr->getStmtClass()) {
13421 case Stmt::UnaryOperatorClass: {
13422 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13423 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13424 TypeExpr = UO->getSubExpr();
13425 continue;
13426 }
13427 return false;
13428 }
13429
13430 case Stmt::DeclRefExprClass: {
13431 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13432 *VD = DRE->getDecl();
13433 return true;
13434 }
13435
13436 case Stmt::IntegerLiteralClass: {
13437 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13438 llvm::APInt MagicValueAPInt = IL->getValue();
13439 if (MagicValueAPInt.getActiveBits() <= 64) {
13440 *MagicValue = MagicValueAPInt.getZExtValue();
13441 return true;
13442 } else
13443 return false;
13444 }
13445
13446 case Stmt::BinaryConditionalOperatorClass:
13447 case Stmt::ConditionalOperatorClass: {
13448 const AbstractConditionalOperator *ACO =
13449 cast<AbstractConditionalOperator>(TypeExpr);
13450 bool Result;
13451 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13452 if (Result)
13453 TypeExpr = ACO->getTrueExpr();
13454 else
13455 TypeExpr = ACO->getFalseExpr();
13456 continue;
13457 }
13458 return false;
13459 }
13460
13461 case Stmt::BinaryOperatorClass: {
13462 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13463 if (BO->getOpcode() == BO_Comma) {
13464 TypeExpr = BO->getRHS();
13465 continue;
13466 }
13467 return false;
13468 }
13469
13470 default:
13471 return false;
13472 }
13473 }
13474}
13475
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013476/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013477///
13478/// \param TypeExpr Expression that specifies a type tag.
13479///
13480/// \param MagicValues Registered magic values.
13481///
13482/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13483/// kind.
13484///
13485/// \param TypeInfo Information about the corresponding C type.
13486///
13487/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013488static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013489 const IdentifierInfo *ArgumentKind,
13490 const Expr *TypeExpr, const ASTContext &Ctx,
13491 const llvm::DenseMap<Sema::TypeTagMagicValue,
13492 Sema::TypeTagData> *MagicValues,
13493 bool &FoundWrongKind,
13494 Sema::TypeTagData &TypeInfo) {
13495 FoundWrongKind = false;
13496
13497 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000013498 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013499
13500 uint64_t MagicValue;
13501
13502 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13503 return false;
13504
13505 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000013506 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013507 if (I->getArgumentKind() != ArgumentKind) {
13508 FoundWrongKind = true;
13509 return false;
13510 }
13511 TypeInfo.Type = I->getMatchingCType();
13512 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13513 TypeInfo.MustBeNull = I->getMustBeNull();
13514 return true;
13515 }
13516 return false;
13517 }
13518
13519 if (!MagicValues)
13520 return false;
13521
13522 llvm::DenseMap<Sema::TypeTagMagicValue,
13523 Sema::TypeTagData>::const_iterator I =
13524 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13525 if (I == MagicValues->end())
13526 return false;
13527
13528 TypeInfo = I->second;
13529 return true;
13530}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013531
13532void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13533 uint64_t MagicValue, QualType Type,
13534 bool LayoutCompatible,
13535 bool MustBeNull) {
13536 if (!TypeTagForDatatypeMagicValues)
13537 TypeTagForDatatypeMagicValues.reset(
13538 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13539
13540 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13541 (*TypeTagForDatatypeMagicValues)[Magic] =
13542 TypeTagData(Type, LayoutCompatible, MustBeNull);
13543}
13544
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013545static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013546 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13547 if (!BT1)
13548 return false;
13549
13550 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13551 if (!BT2)
13552 return false;
13553
13554 BuiltinType::Kind T1Kind = BT1->getKind();
13555 BuiltinType::Kind T2Kind = BT2->getKind();
13556
13557 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
13558 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
13559 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13560 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13561}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013562
13563void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013564 const ArrayRef<const Expr *> ExprArgs,
13565 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013566 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13567 bool IsPointerAttr = Attr->getIsPointer();
13568
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013569 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000013570 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13571 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013572 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000013573 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013574 return;
13575 }
Joel E. Denny81508102018-03-13 14:51:22 +000013576 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013577 bool FoundWrongKind;
13578 TypeTagData TypeInfo;
13579 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13580 TypeTagForDatatypeMagicValues.get(),
13581 FoundWrongKind, TypeInfo)) {
13582 if (FoundWrongKind)
13583 Diag(TypeTagExpr->getExprLoc(),
13584 diag::warn_type_tag_for_datatype_wrong_kind)
13585 << TypeTagExpr->getSourceRange();
13586 return;
13587 }
13588
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013589 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000013590 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13591 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013592 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000013593 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013594 return;
13595 }
Joel E. Denny81508102018-03-13 14:51:22 +000013596 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013597 if (IsPointerAttr) {
13598 // Skip implicit cast of pointer to `void *' (as a function argument).
13599 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000013600 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000013601 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013602 ArgumentExpr = ICE->getSubExpr();
13603 }
13604 QualType ArgumentType = ArgumentExpr->getType();
13605
13606 // Passing a `void*' pointer shouldn't trigger a warning.
13607 if (IsPointerAttr && ArgumentType->isVoidPointerType())
13608 return;
13609
13610 if (TypeInfo.MustBeNull) {
13611 // Type tag with matching void type requires a null pointer.
13612 if (!ArgumentExpr->isNullPointerConstant(Context,
13613 Expr::NPC_ValueDependentIsNotNull)) {
13614 Diag(ArgumentExpr->getExprLoc(),
13615 diag::warn_type_safety_null_pointer_required)
13616 << ArgumentKind->getName()
13617 << ArgumentExpr->getSourceRange()
13618 << TypeTagExpr->getSourceRange();
13619 }
13620 return;
13621 }
13622
13623 QualType RequiredType = TypeInfo.Type;
13624 if (IsPointerAttr)
13625 RequiredType = Context.getPointerType(RequiredType);
13626
13627 bool mismatch = false;
13628 if (!TypeInfo.LayoutCompatible) {
13629 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13630
13631 // C++11 [basic.fundamental] p1:
13632 // Plain char, signed char, and unsigned char are three distinct types.
13633 //
13634 // But we treat plain `char' as equivalent to `signed char' or `unsigned
13635 // char' depending on the current char signedness mode.
13636 if (mismatch)
13637 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13638 RequiredType->getPointeeType())) ||
13639 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13640 mismatch = false;
13641 } else
13642 if (IsPointerAttr)
13643 mismatch = !isLayoutCompatible(Context,
13644 ArgumentType->getPointeeType(),
13645 RequiredType->getPointeeType());
13646 else
13647 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13648
13649 if (mismatch)
13650 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000013651 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013652 << TypeInfo.LayoutCompatible << RequiredType
13653 << ArgumentExpr->getSourceRange()
13654 << TypeTagExpr->getSourceRange();
13655}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013656
13657void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13658 CharUnits Alignment) {
13659 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13660}
13661
13662void Sema::DiagnoseMisalignedMembers() {
13663 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000013664 const NamedDecl *ND = m.RD;
13665 if (ND->getName().empty()) {
13666 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13667 ND = TD;
13668 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013669 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000013670 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013671 }
13672 MisalignedMembers.clear();
13673}
13674
13675void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013676 E = E->IgnoreParens();
13677 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013678 return;
13679 if (isa<UnaryOperator>(E) &&
13680 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13681 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13682 if (isa<MemberExpr>(Op)) {
13683 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13684 MisalignedMember(Op));
13685 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013686 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000013687 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13688 Context.getTypeAlignInChars(
13689 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013690 MisalignedMembers.erase(MA);
13691 }
13692 }
13693}
13694
13695void Sema::RefersToMemberWithReducedAlignment(
13696 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000013697 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13698 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013699 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013700 if (!ME)
13701 return;
13702
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000013703 // No need to check expressions with an __unaligned-qualified type.
13704 if (E->getType().getQualifiers().hasUnaligned())
13705 return;
13706
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013707 // For a chain of MemberExpr like "a.b.c.d" this list
13708 // will keep FieldDecl's like [d, c, b].
13709 SmallVector<FieldDecl *, 4> ReverseMemberChain;
13710 const MemberExpr *TopME = nullptr;
13711 bool AnyIsPacked = false;
13712 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013713 QualType BaseType = ME->getBase()->getType();
13714 if (ME->isArrow())
13715 BaseType = BaseType->getPointeeType();
13716 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000013717 if (RD->isInvalidDecl())
13718 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013719
13720 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013721 auto *FD = dyn_cast<FieldDecl>(MD);
13722 // We do not care about non-data members.
13723 if (!FD || FD->isInvalidDecl())
13724 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013725
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013726 AnyIsPacked =
13727 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13728 ReverseMemberChain.push_back(FD);
13729
13730 TopME = ME;
13731 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13732 } while (ME);
13733 assert(TopME && "We did not compute a topmost MemberExpr!");
13734
13735 // Not the scope of this diagnostic.
13736 if (!AnyIsPacked)
13737 return;
13738
13739 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13740 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13741 // TODO: The innermost base of the member expression may be too complicated.
13742 // For now, just disregard these cases. This is left for future
13743 // improvement.
13744 if (!DRE && !isa<CXXThisExpr>(TopBase))
13745 return;
13746
13747 // Alignment expected by the whole expression.
13748 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13749
13750 // No need to do anything else with this case.
13751 if (ExpectedAlignment.isOne())
13752 return;
13753
13754 // Synthesize offset of the whole access.
13755 CharUnits Offset;
13756 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13757 I++) {
13758 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13759 }
13760
13761 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13762 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13763 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13764
13765 // The base expression of the innermost MemberExpr may give
13766 // stronger guarantees than the class containing the member.
13767 if (DRE && !TopME->isArrow()) {
13768 const ValueDecl *VD = DRE->getDecl();
13769 if (!VD->getType()->isReferenceType())
13770 CompleteObjectAlignment =
13771 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13772 }
13773
13774 // Check if the synthesized offset fulfills the alignment.
13775 if (Offset % ExpectedAlignment != 0 ||
13776 // It may fulfill the offset it but the effective alignment may still be
13777 // lower than the expected expression alignment.
13778 CompleteObjectAlignment < ExpectedAlignment) {
13779 // If this happens, we want to determine a sensible culprit of this.
13780 // Intuitively, watching the chain of member expressions from right to
13781 // left, we start with the required alignment (as required by the field
13782 // type) but some packed attribute in that chain has reduced the alignment.
13783 // It may happen that another packed structure increases it again. But if
13784 // we are here such increase has not been enough. So pointing the first
13785 // FieldDecl that either is packed or else its RecordDecl is,
13786 // seems reasonable.
13787 FieldDecl *FD = nullptr;
13788 CharUnits Alignment;
13789 for (FieldDecl *FDI : ReverseMemberChain) {
13790 if (FDI->hasAttr<PackedAttr>() ||
13791 FDI->getParent()->hasAttr<PackedAttr>()) {
13792 FD = FDI;
13793 Alignment = std::min(
13794 Context.getTypeAlignInChars(FD->getType()),
13795 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13796 break;
13797 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013798 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013799 assert(FD && "We did not find a packed FieldDecl!");
13800 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013801 }
13802}
13803
13804void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13805 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013806
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013807 RefersToMemberWithReducedAlignment(
13808 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13809 _2, _3, _4));
13810}