blob: 31c1b8913b2d7122613ed4227232e883858071a9 [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000015#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000017#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000019#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000024#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000029#include "clang/AST/ExprOpenMP.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000030#include "clang/AST/NSAPI.h"
31#include "clang/AST/OperationKinds.h"
32#include "clang/AST/Stmt.h"
33#include "clang/AST/TemplateBase.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/AST/UnresolvedSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Analysis/Analyses/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000038#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000039#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000040#include "clang/Basic/Diagnostic.h"
41#include "clang/Basic/IdentifierTable.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/LangOptions.h"
44#include "clang/Basic/OpenCLOptions.h"
45#include "clang/Basic/OperatorKinds.h"
46#include "clang/Basic/PartialDiagnostic.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000050#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000051#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000052#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000053#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000054#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000055#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000056#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000058#include "clang/Sema/Ownership.h"
59#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000060#include "clang/Sema/ScopeInfo.h"
61#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000062#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000063#include "llvm/ADT/APFloat.h"
64#include "llvm/ADT/APInt.h"
65#include "llvm/ADT/APSInt.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/DenseMap.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000071#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000072#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000073#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000074#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000075#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/StringRef.h"
77#include "llvm/ADT/StringSwitch.h"
78#include "llvm/ADT/Triple.h"
79#include "llvm/Support/AtomicOrdering.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000082#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000083#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000084#include "llvm/Support/Format.h"
85#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000086#include "llvm/Support/MathExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000087#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000088#include <algorithm>
89#include <cassert>
90#include <cstddef>
91#include <cstdint>
92#include <functional>
93#include <limits>
94#include <string>
95#include <tuple>
96#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000097
Chris Lattnerb87b1b32007-08-10 20:18:51 +000098using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000099using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000100
Chris Lattnera26fb342009-02-18 17:49:48 +0000101SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000105}
106
John McCallbebede42011-02-26 05:39:39 +0000107/// Checks that a call expression's argument count is the desired number.
108/// This is useful when doing custom type-checking. Returns true on error.
109static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110 unsigned argCount = call->getNumArgs();
111 if (argCount == desiredArgCount) return false;
112
113 if (argCount < desiredArgCount)
114 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
115 << 0 /*function call*/ << desiredArgCount << argCount
116 << call->getSourceRange();
117
118 // Highlight all the excess arguments.
119 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
120 call->getArg(argCount - 1)->getLocEnd());
121
122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123 << 0 /*function call*/ << desiredArgCount << argCount
124 << call->getArg(1)->getSourceRange();
125}
126
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000127/// Check that the first argument to __builtin_annotation is an integer
128/// and the second argument is a non-wide string literal.
129static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130 if (checkArgCount(S, TheCall, 2))
131 return true;
132
133 // First argument should be an integer.
134 Expr *ValArg = TheCall->getArg(0);
135 QualType Ty = ValArg->getType();
136 if (!Ty->isIntegerType()) {
137 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
138 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000139 return true;
140 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000141
142 // Second argument should be a constant string.
143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145 if (!Literal || !Literal->isAscii()) {
146 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
147 << StrArg->getSourceRange();
148 return true;
149 }
150
151 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000152 return false;
153}
154
Reid Kleckner30701ed2017-09-05 20:27:35 +0000155static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156 // We need at least one argument.
157 if (TheCall->getNumArgs() < 1) {
158 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
159 << 0 << 1 << TheCall->getNumArgs()
160 << TheCall->getCallee()->getSourceRange();
161 return true;
162 }
163
164 // All arguments should be wide string literals.
165 for (Expr *Arg : TheCall->arguments()) {
166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167 if (!Literal || !Literal->isWide()) {
168 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
169 << Arg->getSourceRange();
170 return true;
171 }
172 }
173
174 return false;
175}
176
Richard Smith6cbd65d2013-07-11 02:27:57 +0000177/// Check that the argument to __builtin_addressof is a glvalue, and set the
178/// result type to the corresponding pointer type.
179static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180 if (checkArgCount(S, TheCall, 1))
181 return true;
182
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000183 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
185 if (ResultType.isNull())
186 return true;
187
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000188 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000189 TheCall->setType(ResultType);
190 return false;
191}
192
John McCall03107a42015-10-29 20:48:01 +0000193static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194 if (checkArgCount(S, TheCall, 3))
195 return true;
196
197 // First two arguments should be integers.
198 for (unsigned I = 0; I < 2; ++I) {
199 Expr *Arg = TheCall->getArg(I);
200 QualType Ty = Arg->getType();
201 if (!Ty->isIntegerType()) {
202 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
203 << Ty << Arg->getSourceRange();
204 return true;
205 }
206 }
207
208 // Third argument should be a pointer to a non-const integer.
209 // IRGen correctly handles volatile, restrict, and address spaces, and
210 // the other qualifiers aren't possible.
211 {
212 Expr *Arg = TheCall->getArg(2);
213 QualType Ty = Arg->getType();
214 const auto *PtrTy = Ty->getAs<PointerType>();
215 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216 !PtrTy->getPointeeType().isConstQualified())) {
217 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
218 << Ty << Arg->getSourceRange();
219 return true;
220 }
221 }
222
223 return false;
224}
225
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000226static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
227 CallExpr *TheCall, unsigned SizeIdx,
228 unsigned DstSizeIdx) {
229 if (TheCall->getNumArgs() <= SizeIdx ||
230 TheCall->getNumArgs() <= DstSizeIdx)
231 return;
232
233 const Expr *SizeArg = TheCall->getArg(SizeIdx);
234 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
235
236 llvm::APSInt Size, DstSize;
237
238 // find out if both sizes are known at compile time
239 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
240 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
241 return;
242
243 if (Size.ule(DstSize))
244 return;
245
246 // confirmed overflow so generate the diagnostic.
247 IdentifierInfo *FnName = FDecl->getIdentifier();
248 SourceLocation SL = TheCall->getLocStart();
249 SourceRange SR = TheCall->getSourceRange();
250
251 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
252}
253
Peter Collingbournef7706832014-12-12 23:41:25 +0000254static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
255 if (checkArgCount(S, BuiltinCall, 2))
256 return true;
257
258 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
259 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
260 Expr *Call = BuiltinCall->getArg(0);
261 Expr *Chain = BuiltinCall->getArg(1);
262
263 if (Call->getStmtClass() != Stmt::CallExprClass) {
264 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
265 << Call->getSourceRange();
266 return true;
267 }
268
269 auto CE = cast<CallExpr>(Call);
270 if (CE->getCallee()->getType()->isBlockPointerType()) {
271 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
272 << Call->getSourceRange();
273 return true;
274 }
275
276 const Decl *TargetDecl = CE->getCalleeDecl();
277 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278 if (FD->getBuiltinID()) {
279 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
280 << Call->getSourceRange();
281 return true;
282 }
283
284 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
286 << Call->getSourceRange();
287 return true;
288 }
289
290 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
291 if (ChainResult.isInvalid())
292 return true;
293 if (!ChainResult.get()->getType()->isPointerType()) {
294 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
295 << Chain->getSourceRange();
296 return true;
297 }
298
David Majnemerced8bdf2015-02-25 17:36:15 +0000299 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000300 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
301 QualType BuiltinTy = S.Context.getFunctionType(
302 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
303 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
304
305 Builtin =
306 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
307
308 BuiltinCall->setType(CE->getType());
309 BuiltinCall->setValueKind(CE->getValueKind());
310 BuiltinCall->setObjectKind(CE->getObjectKind());
311 BuiltinCall->setCallee(Builtin);
312 BuiltinCall->setArg(1, ChainResult.get());
313
314 return false;
315}
316
Reid Kleckner1d59f992015-01-22 01:36:17 +0000317static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
318 Scope::ScopeFlags NeededScopeFlags,
319 unsigned DiagID) {
320 // Scopes aren't available during instantiation. Fortunately, builtin
321 // functions cannot be template args so they cannot be formed through template
322 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000323 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000324 return false;
325
326 Scope *S = SemaRef.getCurScope();
327 while (S && !S->isSEHExceptScope())
328 S = S->getParent();
329 if (!S || !(S->getFlags() & NeededScopeFlags)) {
330 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
331 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
332 << DRE->getDecl()->getIdentifier();
333 return true;
334 }
335
336 return false;
337}
338
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000339static inline bool isBlockPointer(Expr *Arg) {
340 return Arg->getType()->isBlockPointerType();
341}
342
343/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
344/// void*, which is a requirement of device side enqueue.
345static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
346 const BlockPointerType *BPT =
347 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
348 ArrayRef<QualType> Params =
349 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
350 unsigned ArgCounter = 0;
351 bool IllegalParams = false;
352 // Iterate through the block parameters until either one is found that is not
353 // a local void*, or the block is valid.
354 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355 I != E; ++I, ++ArgCounter) {
356 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
358 LangAS::opencl_local) {
359 // Get the location of the error. If a block literal has been passed
360 // (BlockExpr) then we can point straight to the offending argument,
361 // else we just point to the variable reference.
362 SourceLocation ErrorLoc;
363 if (isa<BlockExpr>(BlockArg)) {
364 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
365 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
366 } else if (isa<DeclRefExpr>(BlockArg)) {
367 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
368 }
369 S.Diag(ErrorLoc,
370 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371 IllegalParams = true;
372 }
373 }
374
375 return IllegalParams;
376}
377
Joey Gouly84ae3362017-07-31 15:15:59 +0000378static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
379 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
380 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
381 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
382 return true;
383 }
384 return false;
385}
386
Joey Goulyfa76b492017-08-01 13:27:09 +0000387static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
388 if (checkArgCount(S, TheCall, 2))
389 return true;
390
391 if (checkOpenCLSubgroupExt(S, TheCall))
392 return true;
393
394 // First argument is an ndrange_t type.
395 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000396 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000397 S.Diag(NDRangeArg->getLocStart(),
398 diag::err_opencl_builtin_expected_type)
399 << TheCall->getDirectCallee() << "'ndrange_t'";
400 return true;
401 }
402
403 Expr *BlockArg = TheCall->getArg(1);
404 if (!isBlockPointer(BlockArg)) {
405 S.Diag(BlockArg->getLocStart(),
406 diag::err_opencl_builtin_expected_type)
407 << TheCall->getDirectCallee() << "block";
408 return true;
409 }
410 return checkOpenCLBlockArgs(S, BlockArg);
411}
412
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000413/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
414/// get_kernel_work_group_size
415/// and get_kernel_preferred_work_group_size_multiple builtin functions.
416static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
417 if (checkArgCount(S, TheCall, 1))
418 return true;
419
420 Expr *BlockArg = TheCall->getArg(0);
421 if (!isBlockPointer(BlockArg)) {
422 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000423 diag::err_opencl_builtin_expected_type)
424 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000425 return true;
426 }
427 return checkOpenCLBlockArgs(S, BlockArg);
428}
429
Simon Pilgrim2c518802017-03-30 14:13:19 +0000430/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000431static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432 const QualType &IntType);
433
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000434static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000435 unsigned Start, unsigned End) {
436 bool IllegalParams = false;
437 for (unsigned I = Start; I <= End; ++I)
438 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
439 S.Context.getSizeType());
440 return IllegalParams;
441}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000442
443/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444/// 'local void*' parameter of passed block.
445static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
446 Expr *BlockArg,
447 unsigned NumNonVarArgs) {
448 const BlockPointerType *BPT =
449 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
450 unsigned NumBlockParams =
451 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
452 unsigned TotalNumArgs = TheCall->getNumArgs();
453
454 // For each argument passed to the block, a corresponding uint needs to
455 // be passed to describe the size of the local memory.
456 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
457 S.Diag(TheCall->getLocStart(),
458 diag::err_opencl_enqueue_kernel_local_size_args);
459 return true;
460 }
461
462 // Check that the sizes of the local memory are specified by integers.
463 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
464 TotalNumArgs - 1);
465}
466
467/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
468/// overload formats specified in Table 6.13.17.1.
469/// int enqueue_kernel(queue_t queue,
470/// kernel_enqueue_flags_t flags,
471/// const ndrange_t ndrange,
472/// void (^block)(void))
473/// int enqueue_kernel(queue_t queue,
474/// kernel_enqueue_flags_t flags,
475/// const ndrange_t ndrange,
476/// uint num_events_in_wait_list,
477/// clk_event_t *event_wait_list,
478/// clk_event_t *event_ret,
479/// void (^block)(void))
480/// int enqueue_kernel(queue_t queue,
481/// kernel_enqueue_flags_t flags,
482/// const ndrange_t ndrange,
483/// void (^block)(local void*, ...),
484/// uint size0, ...)
485/// int enqueue_kernel(queue_t queue,
486/// kernel_enqueue_flags_t flags,
487/// const ndrange_t ndrange,
488/// uint num_events_in_wait_list,
489/// clk_event_t *event_wait_list,
490/// clk_event_t *event_ret,
491/// void (^block)(local void*, ...),
492/// uint size0, ...)
493static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
494 unsigned NumArgs = TheCall->getNumArgs();
495
496 if (NumArgs < 4) {
497 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
498 return true;
499 }
500
501 Expr *Arg0 = TheCall->getArg(0);
502 Expr *Arg1 = TheCall->getArg(1);
503 Expr *Arg2 = TheCall->getArg(2);
504 Expr *Arg3 = TheCall->getArg(3);
505
506 // First argument always needs to be a queue_t type.
507 if (!Arg0->getType()->isQueueT()) {
508 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000509 diag::err_opencl_builtin_expected_type)
510 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000511 return true;
512 }
513
514 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
515 if (!Arg1->getType()->isIntegerType()) {
516 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000517 diag::err_opencl_builtin_expected_type)
518 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000519 return true;
520 }
521
522 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000523 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000524 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000525 diag::err_opencl_builtin_expected_type)
526 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000527 return true;
528 }
529
530 // With four arguments, there is only one form that the function could be
531 // called in: no events and no variable arguments.
532 if (NumArgs == 4) {
533 // check that the last argument is the right block type.
534 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000535 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000537 return true;
538 }
539 // we have a block type, check the prototype
540 const BlockPointerType *BPT =
541 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
542 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
543 S.Diag(Arg3->getLocStart(),
544 diag::err_opencl_enqueue_kernel_blocks_no_args);
545 return true;
546 }
547 return false;
548 }
549 // we can have block + varargs.
550 if (isBlockPointer(Arg3))
551 return (checkOpenCLBlockArgs(S, Arg3) ||
552 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
553 // last two cases with either exactly 7 args or 7 args and varargs.
554 if (NumArgs >= 7) {
555 // check common block argument.
556 Expr *Arg6 = TheCall->getArg(6);
557 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000558 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000560 return true;
561 }
562 if (checkOpenCLBlockArgs(S, Arg6))
563 return true;
564
565 // Forth argument has to be any integer type.
566 if (!Arg3->getType()->isIntegerType()) {
567 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000568 diag::err_opencl_builtin_expected_type)
569 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000570 return true;
571 }
572 // check remaining common arguments.
573 Expr *Arg4 = TheCall->getArg(4);
574 Expr *Arg5 = TheCall->getArg(5);
575
Anastasia Stulova2b461202016-11-14 15:34:01 +0000576 // Fifth argument is always passed as a pointer to clk_event_t.
577 if (!Arg4->isNullPointerConstant(S.Context,
578 Expr::NPC_ValueDependentIsNotNull) &&
579 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000580 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000581 diag::err_opencl_builtin_expected_type)
582 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000583 << S.Context.getPointerType(S.Context.OCLClkEventTy);
584 return true;
585 }
586
Anastasia Stulova2b461202016-11-14 15:34:01 +0000587 // Sixth argument is always passed as a pointer to clk_event_t.
588 if (!Arg5->isNullPointerConstant(S.Context,
589 Expr::NPC_ValueDependentIsNotNull) &&
590 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000591 Arg5->getType()->getPointeeType()->isClkEventT())) {
592 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000593 diag::err_opencl_builtin_expected_type)
594 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000595 << S.Context.getPointerType(S.Context.OCLClkEventTy);
596 return true;
597 }
598
599 if (NumArgs == 7)
600 return false;
601
602 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
603 }
604
605 // None of the specific case has been detected, give generic error
606 S.Diag(TheCall->getLocStart(),
607 diag::err_opencl_enqueue_kernel_incorrect_args);
608 return true;
609}
610
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000611/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000612static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000613 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000614}
615
616/// Returns true if pipe element type is different from the pointer.
617static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
618 const Expr *Arg0 = Call->getArg(0);
619 // First argument type should always be pipe.
620 if (!Arg0->getType()->isPipeType()) {
621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000622 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000623 return true;
624 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000625 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000626 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
627 // Validates the access qualifier is compatible with the call.
628 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
629 // read_only and write_only, and assumed to be read_only if no qualifier is
630 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000631 switch (Call->getDirectCallee()->getBuiltinID()) {
632 case Builtin::BIread_pipe:
633 case Builtin::BIreserve_read_pipe:
634 case Builtin::BIcommit_read_pipe:
635 case Builtin::BIwork_group_reserve_read_pipe:
636 case Builtin::BIsub_group_reserve_read_pipe:
637 case Builtin::BIwork_group_commit_read_pipe:
638 case Builtin::BIsub_group_commit_read_pipe:
639 if (!(!AccessQual || AccessQual->isReadOnly())) {
640 S.Diag(Arg0->getLocStart(),
641 diag::err_opencl_builtin_pipe_invalid_access_modifier)
642 << "read_only" << Arg0->getSourceRange();
643 return true;
644 }
645 break;
646 case Builtin::BIwrite_pipe:
647 case Builtin::BIreserve_write_pipe:
648 case Builtin::BIcommit_write_pipe:
649 case Builtin::BIwork_group_reserve_write_pipe:
650 case Builtin::BIsub_group_reserve_write_pipe:
651 case Builtin::BIwork_group_commit_write_pipe:
652 case Builtin::BIsub_group_commit_write_pipe:
653 if (!(AccessQual && AccessQual->isWriteOnly())) {
654 S.Diag(Arg0->getLocStart(),
655 diag::err_opencl_builtin_pipe_invalid_access_modifier)
656 << "write_only" << Arg0->getSourceRange();
657 return true;
658 }
659 break;
660 default:
661 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000662 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 return false;
664}
665
666/// Returns true if pipe element type is different from the pointer.
667static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
668 const Expr *Arg0 = Call->getArg(0);
669 const Expr *ArgIdx = Call->getArg(Idx);
670 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000671 const QualType EltTy = PipeTy->getElementType();
672 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000673 // The Idx argument should be a pointer and the type of the pointer and
674 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000675 if (!ArgTy ||
676 !S.Context.hasSameType(
677 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000678 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000679 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000680 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000681 return true;
682 }
683 return false;
684}
685
686// \brief Performs semantic analysis for the read/write_pipe call.
687// \param S Reference to the semantic analyzer.
688// \param Call A pointer to the builtin call.
689// \return True if a semantic error has been found, false otherwise.
690static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000691 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000693 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000694 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000695 if (checkOpenCLPipeArg(S, Call))
696 return true;
697 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000698 // read/write_pipe(pipe T, T*).
699 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700 if (checkOpenCLPipePacketType(S, Call, 1))
701 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000702 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000703
704 case 4: {
705 if (checkOpenCLPipeArg(S, Call))
706 return true;
707 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000708 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000710 if (!Call->getArg(1)->getType()->isReserveIDT()) {
711 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000712 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000713 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000714 return true;
715 }
716
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000717 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000718 const Expr *Arg2 = Call->getArg(2);
719 if (!Arg2->getType()->isIntegerType() &&
720 !Arg2->getType()->isUnsignedIntegerType()) {
721 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000722 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000723 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000724 return true;
725 }
726
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000727 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000728 if (checkOpenCLPipePacketType(S, Call, 3))
729 return true;
730 } break;
731 default:
732 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000733 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000734 return true;
735 }
736
737 return false;
738}
739
740// \brief Performs a semantic analysis on the {work_group_/sub_group_
741// /_}reserve_{read/write}_pipe
742// \param S Reference to the semantic analyzer.
743// \param Call The call to the builtin function to be analyzed.
744// \return True if a semantic error was found, false otherwise.
745static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
746 if (checkArgCount(S, Call, 2))
747 return true;
748
749 if (checkOpenCLPipeArg(S, Call))
750 return true;
751
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000752 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000753 if (!Call->getArg(1)->getType()->isIntegerType() &&
754 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000756 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000757 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000758 return true;
759 }
760
Joey Gouly922ca232017-08-09 14:52:47 +0000761 // Since return type of reserve_read/write_pipe built-in function is
762 // reserve_id_t, which is not defined in the builtin def file , we used int
763 // as return type and need to override the return type of these functions.
764 Call->setType(S.Context.OCLReserveIDTy);
765
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000766 return false;
767}
768
769// \brief Performs a semantic analysis on {work_group_/sub_group_
770// /_}commit_{read/write}_pipe
771// \param S Reference to the semantic analyzer.
772// \param Call The call to the builtin function to be analyzed.
773// \return True if a semantic error was found, false otherwise.
774static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
775 if (checkArgCount(S, Call, 2))
776 return true;
777
778 if (checkOpenCLPipeArg(S, Call))
779 return true;
780
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000781 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000782 if (!Call->getArg(1)->getType()->isReserveIDT()) {
783 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000784 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000785 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000786 return true;
787 }
788
789 return false;
790}
791
792// \brief Performs a semantic analysis on the call to built-in Pipe
793// Query Functions.
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 SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
798 if (checkArgCount(S, Call, 1))
799 return true;
800
801 if (!Call->getArg(0)->getType()->isPipeType()) {
802 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000803 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000804 return true;
805 }
806
807 return false;
808}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000809
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000810// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000811// \brief Performs semantic analysis for the to_global/local/private call.
812// \param S Reference to the semantic analyzer.
813// \param BuiltinID ID of the builtin function.
814// \param Call A pointer to the builtin call.
815// \return True if a semantic error has been found, false otherwise.
816static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
817 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000818 if (Call->getNumArgs() != 1) {
819 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
820 << Call->getDirectCallee() << Call->getSourceRange();
821 return true;
822 }
823
824 auto RT = Call->getArg(0)->getType();
825 if (!RT->isPointerType() || RT->getPointeeType()
826 .getAddressSpace() == LangAS::opencl_constant) {
827 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
828 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
829 return true;
830 }
831
832 RT = RT->getPointeeType();
833 auto Qual = RT.getQualifiers();
834 switch (BuiltinID) {
835 case Builtin::BIto_global:
836 Qual.setAddressSpace(LangAS::opencl_global);
837 break;
838 case Builtin::BIto_local:
839 Qual.setAddressSpace(LangAS::opencl_local);
840 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000841 case Builtin::BIto_private:
842 Qual.setAddressSpace(LangAS::opencl_private);
843 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000844 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000845 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000846 }
847 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
848 RT.getUnqualifiedType(), Qual)));
849
850 return false;
851}
852
John McCalldadc5752010-08-24 06:29:42 +0000853ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000854Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
855 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000856 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000857
Chris Lattner3be167f2010-10-01 23:23:24 +0000858 // Find out if any arguments are required to be integer constant expressions.
859 unsigned ICEArguments = 0;
860 ASTContext::GetBuiltinTypeError Error;
861 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
862 if (Error != ASTContext::GE_None)
863 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
864
865 // If any arguments are required to be ICE's, check and diagnose.
866 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
867 // Skip arguments not required to be ICE's.
868 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
869
870 llvm::APSInt Result;
871 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
872 return true;
873 ICEArguments &= ~(1 << ArgNo);
874 }
875
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000876 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000877 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000878 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000879 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000880 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000881 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000882 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000883 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000884 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000885 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000886 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000887 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000888 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000889 case Builtin::BI__va_start: {
890 switch (Context.getTargetInfo().getTriple().getArch()) {
891 case llvm::Triple::arm:
892 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000893 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000894 return ExprError();
895 break;
896 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000897 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000898 return ExprError();
899 break;
900 }
901 break;
902 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000903 case Builtin::BI__builtin_isgreater:
904 case Builtin::BI__builtin_isgreaterequal:
905 case Builtin::BI__builtin_isless:
906 case Builtin::BI__builtin_islessequal:
907 case Builtin::BI__builtin_islessgreater:
908 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000909 if (SemaBuiltinUnorderedCompare(TheCall))
910 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000911 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000912 case Builtin::BI__builtin_fpclassify:
913 if (SemaBuiltinFPClassification(TheCall, 6))
914 return ExprError();
915 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000916 case Builtin::BI__builtin_isfinite:
917 case Builtin::BI__builtin_isinf:
918 case Builtin::BI__builtin_isinf_sign:
919 case Builtin::BI__builtin_isnan:
920 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000921 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000922 return ExprError();
923 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000924 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000925 return SemaBuiltinShuffleVector(TheCall);
926 // TheCall will be freed by the smart pointer here, but that's fine, since
927 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000928 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000929 if (SemaBuiltinPrefetch(TheCall))
930 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000931 break;
David Majnemer51169932016-10-31 05:37:48 +0000932 case Builtin::BI__builtin_alloca_with_align:
933 if (SemaBuiltinAllocaWithAlign(TheCall))
934 return ExprError();
935 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000936 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000937 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000938 if (SemaBuiltinAssume(TheCall))
939 return ExprError();
940 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000941 case Builtin::BI__builtin_assume_aligned:
942 if (SemaBuiltinAssumeAligned(TheCall))
943 return ExprError();
944 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000945 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000946 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000947 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000948 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000949 case Builtin::BI__builtin_longjmp:
950 if (SemaBuiltinLongjmp(TheCall))
951 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000952 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000953 case Builtin::BI__builtin_setjmp:
954 if (SemaBuiltinSetjmp(TheCall))
955 return ExprError();
956 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000957 case Builtin::BI_setjmp:
958 case Builtin::BI_setjmpex:
959 if (checkArgCount(*this, TheCall, 1))
960 return true;
961 break;
John McCallbebede42011-02-26 05:39:39 +0000962 case Builtin::BI__builtin_classify_type:
963 if (checkArgCount(*this, TheCall, 1)) return true;
964 TheCall->setType(Context.IntTy);
965 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000966 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000967 if (checkArgCount(*this, TheCall, 1)) return true;
968 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000969 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000970 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000971 case Builtin::BI__sync_fetch_and_add_1:
972 case Builtin::BI__sync_fetch_and_add_2:
973 case Builtin::BI__sync_fetch_and_add_4:
974 case Builtin::BI__sync_fetch_and_add_8:
975 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000976 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000977 case Builtin::BI__sync_fetch_and_sub_1:
978 case Builtin::BI__sync_fetch_and_sub_2:
979 case Builtin::BI__sync_fetch_and_sub_4:
980 case Builtin::BI__sync_fetch_and_sub_8:
981 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000982 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000983 case Builtin::BI__sync_fetch_and_or_1:
984 case Builtin::BI__sync_fetch_and_or_2:
985 case Builtin::BI__sync_fetch_and_or_4:
986 case Builtin::BI__sync_fetch_and_or_8:
987 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000988 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000989 case Builtin::BI__sync_fetch_and_and_1:
990 case Builtin::BI__sync_fetch_and_and_2:
991 case Builtin::BI__sync_fetch_and_and_4:
992 case Builtin::BI__sync_fetch_and_and_8:
993 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000994 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000995 case Builtin::BI__sync_fetch_and_xor_1:
996 case Builtin::BI__sync_fetch_and_xor_2:
997 case Builtin::BI__sync_fetch_and_xor_4:
998 case Builtin::BI__sync_fetch_and_xor_8:
999 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001000 case Builtin::BI__sync_fetch_and_nand:
1001 case Builtin::BI__sync_fetch_and_nand_1:
1002 case Builtin::BI__sync_fetch_and_nand_2:
1003 case Builtin::BI__sync_fetch_and_nand_4:
1004 case Builtin::BI__sync_fetch_and_nand_8:
1005 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001006 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001007 case Builtin::BI__sync_add_and_fetch_1:
1008 case Builtin::BI__sync_add_and_fetch_2:
1009 case Builtin::BI__sync_add_and_fetch_4:
1010 case Builtin::BI__sync_add_and_fetch_8:
1011 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001012 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001013 case Builtin::BI__sync_sub_and_fetch_1:
1014 case Builtin::BI__sync_sub_and_fetch_2:
1015 case Builtin::BI__sync_sub_and_fetch_4:
1016 case Builtin::BI__sync_sub_and_fetch_8:
1017 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001018 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001019 case Builtin::BI__sync_and_and_fetch_1:
1020 case Builtin::BI__sync_and_and_fetch_2:
1021 case Builtin::BI__sync_and_and_fetch_4:
1022 case Builtin::BI__sync_and_and_fetch_8:
1023 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001024 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001025 case Builtin::BI__sync_or_and_fetch_1:
1026 case Builtin::BI__sync_or_and_fetch_2:
1027 case Builtin::BI__sync_or_and_fetch_4:
1028 case Builtin::BI__sync_or_and_fetch_8:
1029 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001030 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001031 case Builtin::BI__sync_xor_and_fetch_1:
1032 case Builtin::BI__sync_xor_and_fetch_2:
1033 case Builtin::BI__sync_xor_and_fetch_4:
1034 case Builtin::BI__sync_xor_and_fetch_8:
1035 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001036 case Builtin::BI__sync_nand_and_fetch:
1037 case Builtin::BI__sync_nand_and_fetch_1:
1038 case Builtin::BI__sync_nand_and_fetch_2:
1039 case Builtin::BI__sync_nand_and_fetch_4:
1040 case Builtin::BI__sync_nand_and_fetch_8:
1041 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001042 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001043 case Builtin::BI__sync_val_compare_and_swap_1:
1044 case Builtin::BI__sync_val_compare_and_swap_2:
1045 case Builtin::BI__sync_val_compare_and_swap_4:
1046 case Builtin::BI__sync_val_compare_and_swap_8:
1047 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001048 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001049 case Builtin::BI__sync_bool_compare_and_swap_1:
1050 case Builtin::BI__sync_bool_compare_and_swap_2:
1051 case Builtin::BI__sync_bool_compare_and_swap_4:
1052 case Builtin::BI__sync_bool_compare_and_swap_8:
1053 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001054 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001055 case Builtin::BI__sync_lock_test_and_set_1:
1056 case Builtin::BI__sync_lock_test_and_set_2:
1057 case Builtin::BI__sync_lock_test_and_set_4:
1058 case Builtin::BI__sync_lock_test_and_set_8:
1059 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001060 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001061 case Builtin::BI__sync_lock_release_1:
1062 case Builtin::BI__sync_lock_release_2:
1063 case Builtin::BI__sync_lock_release_4:
1064 case Builtin::BI__sync_lock_release_8:
1065 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001066 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001067 case Builtin::BI__sync_swap_1:
1068 case Builtin::BI__sync_swap_2:
1069 case Builtin::BI__sync_swap_4:
1070 case Builtin::BI__sync_swap_8:
1071 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001072 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001073 case Builtin::BI__builtin_nontemporal_load:
1074 case Builtin::BI__builtin_nontemporal_store:
1075 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001076#define BUILTIN(ID, TYPE, ATTRS)
1077#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001079 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001080#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001081 case Builtin::BI__annotation:
1082 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1083 return ExprError();
1084 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001085 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001086 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001087 return ExprError();
1088 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001089 case Builtin::BI__builtin_addressof:
1090 if (SemaBuiltinAddressof(*this, TheCall))
1091 return ExprError();
1092 break;
John McCall03107a42015-10-29 20:48:01 +00001093 case Builtin::BI__builtin_add_overflow:
1094 case Builtin::BI__builtin_sub_overflow:
1095 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001096 if (SemaBuiltinOverflow(*this, TheCall))
1097 return ExprError();
1098 break;
Richard Smith760520b2014-06-03 23:27:44 +00001099 case Builtin::BI__builtin_operator_new:
1100 case Builtin::BI__builtin_operator_delete:
1101 if (!getLangOpts().CPlusPlus) {
1102 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1103 << (BuiltinID == Builtin::BI__builtin_operator_new
1104 ? "__builtin_operator_new"
1105 : "__builtin_operator_delete")
1106 << "C++";
1107 return ExprError();
1108 }
1109 // CodeGen assumes it can find the global new and delete to call,
1110 // so ensure that they are declared.
1111 DeclareGlobalNewDelete();
1112 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001113
1114 // check secure string manipulation functions where overflows
1115 // are detectable at compile time
1116 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001117 case Builtin::BI__builtin___memmove_chk:
1118 case Builtin::BI__builtin___memset_chk:
1119 case Builtin::BI__builtin___strlcat_chk:
1120 case Builtin::BI__builtin___strlcpy_chk:
1121 case Builtin::BI__builtin___strncat_chk:
1122 case Builtin::BI__builtin___strncpy_chk:
1123 case Builtin::BI__builtin___stpncpy_chk:
1124 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1125 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001126 case Builtin::BI__builtin___memccpy_chk:
1127 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1128 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001129 case Builtin::BI__builtin___snprintf_chk:
1130 case Builtin::BI__builtin___vsnprintf_chk:
1131 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1132 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001133 case Builtin::BI__builtin_call_with_static_chain:
1134 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1135 return ExprError();
1136 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001137 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001138 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001139 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1140 diag::err_seh___except_block))
1141 return ExprError();
1142 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001143 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001144 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001145 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1146 diag::err_seh___except_filter))
1147 return ExprError();
1148 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001149 case Builtin::BI__GetExceptionInfo:
1150 if (checkArgCount(*this, TheCall, 1))
1151 return ExprError();
1152
1153 if (CheckCXXThrowOperand(
1154 TheCall->getLocStart(),
1155 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1156 TheCall))
1157 return ExprError();
1158
1159 TheCall->setType(Context.VoidPtrTy);
1160 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001161 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001162 case Builtin::BIread_pipe:
1163 case Builtin::BIwrite_pipe:
1164 // Since those two functions are declared with var args, we need a semantic
1165 // check for the argument.
1166 if (SemaBuiltinRWPipe(*this, TheCall))
1167 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001168 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001169 break;
1170 case Builtin::BIreserve_read_pipe:
1171 case Builtin::BIreserve_write_pipe:
1172 case Builtin::BIwork_group_reserve_read_pipe:
1173 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001174 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1175 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001176 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001177 case Builtin::BIsub_group_reserve_read_pipe:
1178 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001179 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1180 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001181 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001182 break;
1183 case Builtin::BIcommit_read_pipe:
1184 case Builtin::BIcommit_write_pipe:
1185 case Builtin::BIwork_group_commit_read_pipe:
1186 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001187 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1188 return ExprError();
1189 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001190 case Builtin::BIsub_group_commit_read_pipe:
1191 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001192 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1193 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001194 return ExprError();
1195 break;
1196 case Builtin::BIget_pipe_num_packets:
1197 case Builtin::BIget_pipe_max_packets:
1198 if (SemaBuiltinPipePackets(*this, TheCall))
1199 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001200 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001201 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001202 case Builtin::BIto_global:
1203 case Builtin::BIto_local:
1204 case Builtin::BIto_private:
1205 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1206 return ExprError();
1207 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001208 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1209 case Builtin::BIenqueue_kernel:
1210 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1211 return ExprError();
1212 break;
1213 case Builtin::BIget_kernel_work_group_size:
1214 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1215 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1216 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001217 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001218 break;
1219 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1220 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1221 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1222 return ExprError();
1223 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001224 case Builtin::BI__builtin_os_log_format:
1225 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001226 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001227 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001228 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001229 }
Richard Smith760520b2014-06-03 23:27:44 +00001230
Nate Begeman4904e322010-06-08 02:47:44 +00001231 // Since the target specific builtins for each arch overlap, only check those
1232 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001233 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001234 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001235 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001236 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001237 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001238 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001239 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1240 return ExprError();
1241 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001242 case llvm::Triple::aarch64:
1243 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001244 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001245 return ExprError();
1246 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001247 case llvm::Triple::mips:
1248 case llvm::Triple::mipsel:
1249 case llvm::Triple::mips64:
1250 case llvm::Triple::mips64el:
1251 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1252 return ExprError();
1253 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001254 case llvm::Triple::systemz:
1255 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1256 return ExprError();
1257 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001258 case llvm::Triple::x86:
1259 case llvm::Triple::x86_64:
1260 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1261 return ExprError();
1262 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001263 case llvm::Triple::ppc:
1264 case llvm::Triple::ppc64:
1265 case llvm::Triple::ppc64le:
1266 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1267 return ExprError();
1268 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001269 default:
1270 break;
1271 }
1272 }
1273
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001274 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001275}
1276
Nate Begeman91e1fea2010-06-14 05:21:25 +00001277// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001278static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001279 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001280 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001281 switch (Type.getEltType()) {
1282 case NeonTypeFlags::Int8:
1283 case NeonTypeFlags::Poly8:
1284 return shift ? 7 : (8 << IsQuad) - 1;
1285 case NeonTypeFlags::Int16:
1286 case NeonTypeFlags::Poly16:
1287 return shift ? 15 : (4 << IsQuad) - 1;
1288 case NeonTypeFlags::Int32:
1289 return shift ? 31 : (2 << IsQuad) - 1;
1290 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001291 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001292 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001293 case NeonTypeFlags::Poly128:
1294 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001295 case NeonTypeFlags::Float16:
1296 assert(!shift && "cannot shift float types!");
1297 return (4 << IsQuad) - 1;
1298 case NeonTypeFlags::Float32:
1299 assert(!shift && "cannot shift float types!");
1300 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001301 case NeonTypeFlags::Float64:
1302 assert(!shift && "cannot shift float types!");
1303 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001304 }
David Blaikie8a40f702012-01-17 06:56:22 +00001305 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001306}
1307
Bob Wilsone4d77232011-11-08 05:04:11 +00001308/// getNeonEltType - Return the QualType corresponding to the elements of
1309/// the vector type specified by the NeonTypeFlags. This is used to check
1310/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001311static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001312 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001313 switch (Flags.getEltType()) {
1314 case NeonTypeFlags::Int8:
1315 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1316 case NeonTypeFlags::Int16:
1317 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1318 case NeonTypeFlags::Int32:
1319 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1320 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001321 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001322 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1323 else
1324 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1325 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001326 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001327 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001328 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001329 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001330 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001331 if (IsInt64Long)
1332 return Context.UnsignedLongTy;
1333 else
1334 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001335 case NeonTypeFlags::Poly128:
1336 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001337 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001338 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001339 case NeonTypeFlags::Float32:
1340 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001341 case NeonTypeFlags::Float64:
1342 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001343 }
David Blaikie8a40f702012-01-17 06:56:22 +00001344 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001345}
1346
Tim Northover12670412014-02-19 10:37:05 +00001347bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001348 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001349 uint64_t mask = 0;
1350 unsigned TV = 0;
1351 int PtrArgNum = -1;
1352 bool HasConstPtr = false;
1353 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001354#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001355#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001356#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001357#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001358 }
1359
1360 // For NEON intrinsics which are overloaded on vector element type, validate
1361 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001362 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001363 if (mask) {
1364 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1365 return true;
1366
1367 TV = Result.getLimitedValue(64);
1368 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1369 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001370 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001371 }
1372
1373 if (PtrArgNum >= 0) {
1374 // Check that pointer arguments have the specified type.
1375 Expr *Arg = TheCall->getArg(PtrArgNum);
1376 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1377 Arg = ICE->getSubExpr();
1378 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1379 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001380
Tim Northovera2ee4332014-03-29 15:09:45 +00001381 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001382 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1383 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001384 bool IsInt64Long =
1385 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1386 QualType EltTy =
1387 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001388 if (HasConstPtr)
1389 EltTy = EltTy.withConst();
1390 QualType LHSTy = Context.getPointerType(EltTy);
1391 AssignConvertType ConvTy;
1392 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1393 if (RHS.isInvalid())
1394 return true;
1395 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1396 RHS.get(), AA_Assigning))
1397 return true;
1398 }
1399
1400 // For NEON intrinsics which take an immediate value as part of the
1401 // instruction, range check them here.
1402 unsigned i = 0, l = 0, u = 0;
1403 switch (BuiltinID) {
1404 default:
1405 return false;
Tim Northover12670412014-02-19 10:37:05 +00001406#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001407#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001408#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001409#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001410 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001411
Richard Sandiford28940af2014-04-16 08:47:51 +00001412 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001413}
1414
Tim Northovera2ee4332014-03-29 15:09:45 +00001415bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1416 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001417 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001418 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001419 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001420 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001421 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001422 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1423 BuiltinID == AArch64::BI__builtin_arm_strex ||
1424 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001425 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001426 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001427 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1428 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1429 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001430
1431 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1432
1433 // Ensure that we have the proper number of arguments.
1434 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1435 return true;
1436
1437 // Inspect the pointer argument of the atomic builtin. This should always be
1438 // a pointer type, whose element is an integral scalar or pointer type.
1439 // Because it is a pointer type, we don't have to worry about any implicit
1440 // casts here.
1441 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1442 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1443 if (PointerArgRes.isInvalid())
1444 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001445 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001446
1447 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1448 if (!pointerType) {
1449 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1450 << PointerArg->getType() << PointerArg->getSourceRange();
1451 return true;
1452 }
1453
1454 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1455 // task is to insert the appropriate casts into the AST. First work out just
1456 // what the appropriate type is.
1457 QualType ValType = pointerType->getPointeeType();
1458 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1459 if (IsLdrex)
1460 AddrType.addConst();
1461
1462 // Issue a warning if the cast is dodgy.
1463 CastKind CastNeeded = CK_NoOp;
1464 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1465 CastNeeded = CK_BitCast;
1466 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1467 << PointerArg->getType()
1468 << Context.getPointerType(AddrType)
1469 << AA_Passing << PointerArg->getSourceRange();
1470 }
1471
1472 // Finally, do the cast and replace the argument with the corrected version.
1473 AddrType = Context.getPointerType(AddrType);
1474 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1475 if (PointerArgRes.isInvalid())
1476 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001477 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001478
1479 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1480
1481 // In general, we allow ints, floats and pointers to be loaded and stored.
1482 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1483 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1484 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1485 << PointerArg->getType() << PointerArg->getSourceRange();
1486 return true;
1487 }
1488
1489 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001490 if (Context.getTypeSize(ValType) > MaxWidth) {
1491 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001492 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1493 << PointerArg->getType() << PointerArg->getSourceRange();
1494 return true;
1495 }
1496
1497 switch (ValType.getObjCLifetime()) {
1498 case Qualifiers::OCL_None:
1499 case Qualifiers::OCL_ExplicitNone:
1500 // okay
1501 break;
1502
1503 case Qualifiers::OCL_Weak:
1504 case Qualifiers::OCL_Strong:
1505 case Qualifiers::OCL_Autoreleasing:
1506 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1507 << ValType << PointerArg->getSourceRange();
1508 return true;
1509 }
1510
Tim Northover6aacd492013-07-16 09:47:53 +00001511 if (IsLdrex) {
1512 TheCall->setType(ValType);
1513 return false;
1514 }
1515
1516 // Initialize the argument to be stored.
1517 ExprResult ValArg = TheCall->getArg(0);
1518 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1519 Context, ValType, /*consume*/ false);
1520 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1521 if (ValArg.isInvalid())
1522 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001523 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001524
1525 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1526 // but the custom checker bypasses all default analysis.
1527 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001528 return false;
1529}
1530
Nate Begeman4904e322010-06-08 02:47:44 +00001531bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001532 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001533 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1534 BuiltinID == ARM::BI__builtin_arm_strex ||
1535 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001536 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001537 }
1538
Yi Kong26d104a2014-08-13 19:18:14 +00001539 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1540 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1541 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1542 }
1543
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001544 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1545 BuiltinID == ARM::BI__builtin_arm_wsr64)
1546 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1547
1548 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1549 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1550 BuiltinID == ARM::BI__builtin_arm_wsr ||
1551 BuiltinID == ARM::BI__builtin_arm_wsrp)
1552 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1553
Tim Northover12670412014-02-19 10:37:05 +00001554 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1555 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001556
Yi Kong4efadfb2014-07-03 16:01:25 +00001557 // For intrinsics which take an immediate value as part of the instruction,
1558 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001559 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001560 switch (BuiltinID) {
1561 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001562 case ARM::BI__builtin_arm_ssat:
1563 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1564 case ARM::BI__builtin_arm_usat:
1565 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1566 case ARM::BI__builtin_arm_ssat16:
1567 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1568 case ARM::BI__builtin_arm_usat16:
1569 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001570 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001571 case ARM::BI__builtin_arm_vcvtr_d:
1572 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001573 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001574 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001575 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001576 case ARM::BI__builtin_arm_dbg:
1577 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001578 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001579}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001580
Tim Northover573cbee2014-05-24 12:52:07 +00001581bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001582 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001583 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001584 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1585 BuiltinID == AArch64::BI__builtin_arm_strex ||
1586 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001587 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1588 }
1589
Yi Konga5548432014-08-13 19:18:20 +00001590 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1591 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1592 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1593 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1594 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1595 }
1596
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001597 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1598 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001599 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001600
1601 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1602 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1603 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1604 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1605 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1606
Tim Northovera2ee4332014-03-29 15:09:45 +00001607 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1608 return true;
1609
Yi Kong19a29ac2014-07-17 10:52:06 +00001610 // For intrinsics which take an immediate value as part of the instruction,
1611 // range check them here.
1612 unsigned i = 0, l = 0, u = 0;
1613 switch (BuiltinID) {
1614 default: return false;
1615 case AArch64::BI__builtin_arm_dmb:
1616 case AArch64::BI__builtin_arm_dsb:
1617 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1618 }
1619
Yi Kong19a29ac2014-07-17 10:52:06 +00001620 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001621}
1622
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001623// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1624// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1625// ordering for DSP is unspecified. MSA is ordered by the data format used
1626// by the underlying instruction i.e., df/m, df/n and then by size.
1627//
1628// FIXME: The size tests here should instead be tablegen'd along with the
1629// definitions from include/clang/Basic/BuiltinsMips.def.
1630// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1631// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001632bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001633 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001634 switch (BuiltinID) {
1635 default: return false;
1636 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1637 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001638 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1639 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1640 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1641 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1642 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001643 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1644 // df/m field.
1645 // These intrinsics take an unsigned 3 bit immediate.
1646 case Mips::BI__builtin_msa_bclri_b:
1647 case Mips::BI__builtin_msa_bnegi_b:
1648 case Mips::BI__builtin_msa_bseti_b:
1649 case Mips::BI__builtin_msa_sat_s_b:
1650 case Mips::BI__builtin_msa_sat_u_b:
1651 case Mips::BI__builtin_msa_slli_b:
1652 case Mips::BI__builtin_msa_srai_b:
1653 case Mips::BI__builtin_msa_srari_b:
1654 case Mips::BI__builtin_msa_srli_b:
1655 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1656 case Mips::BI__builtin_msa_binsli_b:
1657 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1658 // These intrinsics take an unsigned 4 bit immediate.
1659 case Mips::BI__builtin_msa_bclri_h:
1660 case Mips::BI__builtin_msa_bnegi_h:
1661 case Mips::BI__builtin_msa_bseti_h:
1662 case Mips::BI__builtin_msa_sat_s_h:
1663 case Mips::BI__builtin_msa_sat_u_h:
1664 case Mips::BI__builtin_msa_slli_h:
1665 case Mips::BI__builtin_msa_srai_h:
1666 case Mips::BI__builtin_msa_srari_h:
1667 case Mips::BI__builtin_msa_srli_h:
1668 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1669 case Mips::BI__builtin_msa_binsli_h:
1670 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1671 // These intrinsics take an unsigned 5 bit immedate.
1672 // The first block of intrinsics actually have an unsigned 5 bit field,
1673 // not a df/n field.
1674 case Mips::BI__builtin_msa_clei_u_b:
1675 case Mips::BI__builtin_msa_clei_u_h:
1676 case Mips::BI__builtin_msa_clei_u_w:
1677 case Mips::BI__builtin_msa_clei_u_d:
1678 case Mips::BI__builtin_msa_clti_u_b:
1679 case Mips::BI__builtin_msa_clti_u_h:
1680 case Mips::BI__builtin_msa_clti_u_w:
1681 case Mips::BI__builtin_msa_clti_u_d:
1682 case Mips::BI__builtin_msa_maxi_u_b:
1683 case Mips::BI__builtin_msa_maxi_u_h:
1684 case Mips::BI__builtin_msa_maxi_u_w:
1685 case Mips::BI__builtin_msa_maxi_u_d:
1686 case Mips::BI__builtin_msa_mini_u_b:
1687 case Mips::BI__builtin_msa_mini_u_h:
1688 case Mips::BI__builtin_msa_mini_u_w:
1689 case Mips::BI__builtin_msa_mini_u_d:
1690 case Mips::BI__builtin_msa_addvi_b:
1691 case Mips::BI__builtin_msa_addvi_h:
1692 case Mips::BI__builtin_msa_addvi_w:
1693 case Mips::BI__builtin_msa_addvi_d:
1694 case Mips::BI__builtin_msa_bclri_w:
1695 case Mips::BI__builtin_msa_bnegi_w:
1696 case Mips::BI__builtin_msa_bseti_w:
1697 case Mips::BI__builtin_msa_sat_s_w:
1698 case Mips::BI__builtin_msa_sat_u_w:
1699 case Mips::BI__builtin_msa_slli_w:
1700 case Mips::BI__builtin_msa_srai_w:
1701 case Mips::BI__builtin_msa_srari_w:
1702 case Mips::BI__builtin_msa_srli_w:
1703 case Mips::BI__builtin_msa_srlri_w:
1704 case Mips::BI__builtin_msa_subvi_b:
1705 case Mips::BI__builtin_msa_subvi_h:
1706 case Mips::BI__builtin_msa_subvi_w:
1707 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1708 case Mips::BI__builtin_msa_binsli_w:
1709 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1710 // These intrinsics take an unsigned 6 bit immediate.
1711 case Mips::BI__builtin_msa_bclri_d:
1712 case Mips::BI__builtin_msa_bnegi_d:
1713 case Mips::BI__builtin_msa_bseti_d:
1714 case Mips::BI__builtin_msa_sat_s_d:
1715 case Mips::BI__builtin_msa_sat_u_d:
1716 case Mips::BI__builtin_msa_slli_d:
1717 case Mips::BI__builtin_msa_srai_d:
1718 case Mips::BI__builtin_msa_srari_d:
1719 case Mips::BI__builtin_msa_srli_d:
1720 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1721 case Mips::BI__builtin_msa_binsli_d:
1722 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1723 // These intrinsics take a signed 5 bit immediate.
1724 case Mips::BI__builtin_msa_ceqi_b:
1725 case Mips::BI__builtin_msa_ceqi_h:
1726 case Mips::BI__builtin_msa_ceqi_w:
1727 case Mips::BI__builtin_msa_ceqi_d:
1728 case Mips::BI__builtin_msa_clti_s_b:
1729 case Mips::BI__builtin_msa_clti_s_h:
1730 case Mips::BI__builtin_msa_clti_s_w:
1731 case Mips::BI__builtin_msa_clti_s_d:
1732 case Mips::BI__builtin_msa_clei_s_b:
1733 case Mips::BI__builtin_msa_clei_s_h:
1734 case Mips::BI__builtin_msa_clei_s_w:
1735 case Mips::BI__builtin_msa_clei_s_d:
1736 case Mips::BI__builtin_msa_maxi_s_b:
1737 case Mips::BI__builtin_msa_maxi_s_h:
1738 case Mips::BI__builtin_msa_maxi_s_w:
1739 case Mips::BI__builtin_msa_maxi_s_d:
1740 case Mips::BI__builtin_msa_mini_s_b:
1741 case Mips::BI__builtin_msa_mini_s_h:
1742 case Mips::BI__builtin_msa_mini_s_w:
1743 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1744 // These intrinsics take an unsigned 8 bit immediate.
1745 case Mips::BI__builtin_msa_andi_b:
1746 case Mips::BI__builtin_msa_nori_b:
1747 case Mips::BI__builtin_msa_ori_b:
1748 case Mips::BI__builtin_msa_shf_b:
1749 case Mips::BI__builtin_msa_shf_h:
1750 case Mips::BI__builtin_msa_shf_w:
1751 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1752 case Mips::BI__builtin_msa_bseli_b:
1753 case Mips::BI__builtin_msa_bmnzi_b:
1754 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1755 // df/n format
1756 // These intrinsics take an unsigned 4 bit immediate.
1757 case Mips::BI__builtin_msa_copy_s_b:
1758 case Mips::BI__builtin_msa_copy_u_b:
1759 case Mips::BI__builtin_msa_insve_b:
1760 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001761 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1762 // These intrinsics take an unsigned 3 bit immediate.
1763 case Mips::BI__builtin_msa_copy_s_h:
1764 case Mips::BI__builtin_msa_copy_u_h:
1765 case Mips::BI__builtin_msa_insve_h:
1766 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001767 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1768 // These intrinsics take an unsigned 2 bit immediate.
1769 case Mips::BI__builtin_msa_copy_s_w:
1770 case Mips::BI__builtin_msa_copy_u_w:
1771 case Mips::BI__builtin_msa_insve_w:
1772 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001773 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1774 // These intrinsics take an unsigned 1 bit immediate.
1775 case Mips::BI__builtin_msa_copy_s_d:
1776 case Mips::BI__builtin_msa_copy_u_d:
1777 case Mips::BI__builtin_msa_insve_d:
1778 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001779 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1780 // Memory offsets and immediate loads.
1781 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001782 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001783 case Mips::BI__builtin_msa_ldi_h:
1784 case Mips::BI__builtin_msa_ldi_w:
1785 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1786 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1787 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1788 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1789 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1790 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1791 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1792 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1793 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001794 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001795
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001796 if (!m)
1797 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1798
1799 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1800 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001801}
1802
Kit Bartone50adcb2015-03-30 19:40:59 +00001803bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1804 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001805 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1806 BuiltinID == PPC::BI__builtin_divdeu ||
1807 BuiltinID == PPC::BI__builtin_bpermd;
1808 bool IsTarget64Bit = Context.getTargetInfo()
1809 .getTypeWidth(Context
1810 .getTargetInfo()
1811 .getIntPtrType()) == 64;
1812 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1813 BuiltinID == PPC::BI__builtin_divweu ||
1814 BuiltinID == PPC::BI__builtin_divde ||
1815 BuiltinID == PPC::BI__builtin_divdeu;
1816
1817 if (Is64BitBltin && !IsTarget64Bit)
1818 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1819 << TheCall->getSourceRange();
1820
1821 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1822 (BuiltinID == PPC::BI__builtin_bpermd &&
1823 !Context.getTargetInfo().hasFeature("bpermd")))
1824 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1825 << TheCall->getSourceRange();
1826
Kit Bartone50adcb2015-03-30 19:40:59 +00001827 switch (BuiltinID) {
1828 default: return false;
1829 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1830 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1831 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1832 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1833 case PPC::BI__builtin_tbegin:
1834 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1835 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1836 case PPC::BI__builtin_tabortwc:
1837 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1838 case PPC::BI__builtin_tabortwci:
1839 case PPC::BI__builtin_tabortdci:
1840 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1841 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001842 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001843 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001844 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001845 }
1846 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1847}
1848
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001849bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1850 CallExpr *TheCall) {
1851 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1852 Expr *Arg = TheCall->getArg(0);
1853 llvm::APSInt AbortCode(32);
1854 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1855 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1856 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1857 << Arg->getSourceRange();
1858 }
1859
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001860 // For intrinsics which take an immediate value as part of the instruction,
1861 // range check them here.
1862 unsigned i = 0, l = 0, u = 0;
1863 switch (BuiltinID) {
1864 default: return false;
1865 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1866 case SystemZ::BI__builtin_s390_verimb:
1867 case SystemZ::BI__builtin_s390_verimh:
1868 case SystemZ::BI__builtin_s390_verimf:
1869 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1870 case SystemZ::BI__builtin_s390_vfaeb:
1871 case SystemZ::BI__builtin_s390_vfaeh:
1872 case SystemZ::BI__builtin_s390_vfaef:
1873 case SystemZ::BI__builtin_s390_vfaebs:
1874 case SystemZ::BI__builtin_s390_vfaehs:
1875 case SystemZ::BI__builtin_s390_vfaefs:
1876 case SystemZ::BI__builtin_s390_vfaezb:
1877 case SystemZ::BI__builtin_s390_vfaezh:
1878 case SystemZ::BI__builtin_s390_vfaezf:
1879 case SystemZ::BI__builtin_s390_vfaezbs:
1880 case SystemZ::BI__builtin_s390_vfaezhs:
1881 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001882 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001883 case SystemZ::BI__builtin_s390_vfidb:
1884 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1885 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001886 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001887 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1888 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1889 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1890 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1891 case SystemZ::BI__builtin_s390_vstrcb:
1892 case SystemZ::BI__builtin_s390_vstrch:
1893 case SystemZ::BI__builtin_s390_vstrcf:
1894 case SystemZ::BI__builtin_s390_vstrczb:
1895 case SystemZ::BI__builtin_s390_vstrczh:
1896 case SystemZ::BI__builtin_s390_vstrczf:
1897 case SystemZ::BI__builtin_s390_vstrcbs:
1898 case SystemZ::BI__builtin_s390_vstrchs:
1899 case SystemZ::BI__builtin_s390_vstrcfs:
1900 case SystemZ::BI__builtin_s390_vstrczbs:
1901 case SystemZ::BI__builtin_s390_vstrczhs:
1902 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001903 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1904 case SystemZ::BI__builtin_s390_vfminsb:
1905 case SystemZ::BI__builtin_s390_vfmaxsb:
1906 case SystemZ::BI__builtin_s390_vfmindb:
1907 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001908 }
1909 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001910}
1911
Craig Topper5ba2c502015-11-07 08:08:31 +00001912/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1913/// This checks that the target supports __builtin_cpu_supports and
1914/// that the string argument is constant and valid.
1915static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1916 Expr *Arg = TheCall->getArg(0);
1917
1918 // Check if the argument is a string literal.
1919 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1920 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1921 << Arg->getSourceRange();
1922
1923 // Check the contents of the string.
1924 StringRef Feature =
1925 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1926 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1927 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1928 << Arg->getSourceRange();
1929 return false;
1930}
1931
Craig Topper699ae0c2017-08-10 20:28:30 +00001932/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1933/// This checks that the target supports __builtin_cpu_is and
1934/// that the string argument is constant and valid.
1935static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1936 Expr *Arg = TheCall->getArg(0);
1937
1938 // Check if the argument is a string literal.
1939 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1940 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1941 << Arg->getSourceRange();
1942
1943 // Check the contents of the string.
1944 StringRef Feature =
1945 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1946 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1947 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1948 << Arg->getSourceRange();
1949 return false;
1950}
1951
Craig Toppera7e253e2016-09-23 04:48:31 +00001952// Check if the rounding mode is legal.
1953bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1954 // Indicates if this instruction has rounding control or just SAE.
1955 bool HasRC = false;
1956
1957 unsigned ArgNum = 0;
1958 switch (BuiltinID) {
1959 default:
1960 return false;
1961 case X86::BI__builtin_ia32_vcvttsd2si32:
1962 case X86::BI__builtin_ia32_vcvttsd2si64:
1963 case X86::BI__builtin_ia32_vcvttsd2usi32:
1964 case X86::BI__builtin_ia32_vcvttsd2usi64:
1965 case X86::BI__builtin_ia32_vcvttss2si32:
1966 case X86::BI__builtin_ia32_vcvttss2si64:
1967 case X86::BI__builtin_ia32_vcvttss2usi32:
1968 case X86::BI__builtin_ia32_vcvttss2usi64:
1969 ArgNum = 1;
1970 break;
1971 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1972 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1973 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1974 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1975 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1976 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1977 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1978 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1979 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1980 case X86::BI__builtin_ia32_exp2pd_mask:
1981 case X86::BI__builtin_ia32_exp2ps_mask:
1982 case X86::BI__builtin_ia32_getexppd512_mask:
1983 case X86::BI__builtin_ia32_getexpps512_mask:
1984 case X86::BI__builtin_ia32_rcp28pd_mask:
1985 case X86::BI__builtin_ia32_rcp28ps_mask:
1986 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1987 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1988 case X86::BI__builtin_ia32_vcomisd:
1989 case X86::BI__builtin_ia32_vcomiss:
1990 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1991 ArgNum = 3;
1992 break;
1993 case X86::BI__builtin_ia32_cmppd512_mask:
1994 case X86::BI__builtin_ia32_cmpps512_mask:
1995 case X86::BI__builtin_ia32_cmpsd_mask:
1996 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001997 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001998 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1999 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002000 case X86::BI__builtin_ia32_maxpd512_mask:
2001 case X86::BI__builtin_ia32_maxps512_mask:
2002 case X86::BI__builtin_ia32_maxsd_round_mask:
2003 case X86::BI__builtin_ia32_maxss_round_mask:
2004 case X86::BI__builtin_ia32_minpd512_mask:
2005 case X86::BI__builtin_ia32_minps512_mask:
2006 case X86::BI__builtin_ia32_minsd_round_mask:
2007 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002008 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2009 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2010 case X86::BI__builtin_ia32_reducepd512_mask:
2011 case X86::BI__builtin_ia32_reduceps512_mask:
2012 case X86::BI__builtin_ia32_rndscalepd_mask:
2013 case X86::BI__builtin_ia32_rndscaleps_mask:
2014 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2015 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2016 ArgNum = 4;
2017 break;
2018 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002019 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002020 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002021 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002022 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002023 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002024 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002025 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002026 case X86::BI__builtin_ia32_rangepd512_mask:
2027 case X86::BI__builtin_ia32_rangeps512_mask:
2028 case X86::BI__builtin_ia32_rangesd128_round_mask:
2029 case X86::BI__builtin_ia32_rangess128_round_mask:
2030 case X86::BI__builtin_ia32_reducesd_mask:
2031 case X86::BI__builtin_ia32_reducess_mask:
2032 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2033 case X86::BI__builtin_ia32_rndscaless_round_mask:
2034 ArgNum = 5;
2035 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002036 case X86::BI__builtin_ia32_vcvtsd2si64:
2037 case X86::BI__builtin_ia32_vcvtsd2si32:
2038 case X86::BI__builtin_ia32_vcvtsd2usi32:
2039 case X86::BI__builtin_ia32_vcvtsd2usi64:
2040 case X86::BI__builtin_ia32_vcvtss2si32:
2041 case X86::BI__builtin_ia32_vcvtss2si64:
2042 case X86::BI__builtin_ia32_vcvtss2usi32:
2043 case X86::BI__builtin_ia32_vcvtss2usi64:
2044 ArgNum = 1;
2045 HasRC = true;
2046 break;
Craig Topper8e066312016-11-07 07:01:09 +00002047 case X86::BI__builtin_ia32_cvtsi2sd64:
2048 case X86::BI__builtin_ia32_cvtsi2ss32:
2049 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002050 case X86::BI__builtin_ia32_cvtusi2sd64:
2051 case X86::BI__builtin_ia32_cvtusi2ss32:
2052 case X86::BI__builtin_ia32_cvtusi2ss64:
2053 ArgNum = 2;
2054 HasRC = true;
2055 break;
2056 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2057 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2058 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2059 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2060 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2061 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2062 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2063 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2064 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2065 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2066 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002067 case X86::BI__builtin_ia32_sqrtpd512_mask:
2068 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002069 ArgNum = 3;
2070 HasRC = true;
2071 break;
2072 case X86::BI__builtin_ia32_addpd512_mask:
2073 case X86::BI__builtin_ia32_addps512_mask:
2074 case X86::BI__builtin_ia32_divpd512_mask:
2075 case X86::BI__builtin_ia32_divps512_mask:
2076 case X86::BI__builtin_ia32_mulpd512_mask:
2077 case X86::BI__builtin_ia32_mulps512_mask:
2078 case X86::BI__builtin_ia32_subpd512_mask:
2079 case X86::BI__builtin_ia32_subps512_mask:
2080 case X86::BI__builtin_ia32_addss_round_mask:
2081 case X86::BI__builtin_ia32_addsd_round_mask:
2082 case X86::BI__builtin_ia32_divss_round_mask:
2083 case X86::BI__builtin_ia32_divsd_round_mask:
2084 case X86::BI__builtin_ia32_mulss_round_mask:
2085 case X86::BI__builtin_ia32_mulsd_round_mask:
2086 case X86::BI__builtin_ia32_subss_round_mask:
2087 case X86::BI__builtin_ia32_subsd_round_mask:
2088 case X86::BI__builtin_ia32_scalefpd512_mask:
2089 case X86::BI__builtin_ia32_scalefps512_mask:
2090 case X86::BI__builtin_ia32_scalefsd_round_mask:
2091 case X86::BI__builtin_ia32_scalefss_round_mask:
2092 case X86::BI__builtin_ia32_getmantpd512_mask:
2093 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002094 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2095 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2096 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002097 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2098 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2099 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2100 case X86::BI__builtin_ia32_vfmaddps512_mask:
2101 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2102 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2103 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2104 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2105 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2106 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2107 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2108 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2109 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2110 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2111 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2112 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2113 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2114 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2115 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2116 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2117 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2118 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2119 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2120 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2121 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2122 case X86::BI__builtin_ia32_vfmaddss3_mask:
2123 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2124 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2125 ArgNum = 4;
2126 HasRC = true;
2127 break;
2128 case X86::BI__builtin_ia32_getmantsd_round_mask:
2129 case X86::BI__builtin_ia32_getmantss_round_mask:
2130 ArgNum = 5;
2131 HasRC = true;
2132 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002133 }
2134
2135 llvm::APSInt Result;
2136
2137 // We can't check the value of a dependent argument.
2138 Expr *Arg = TheCall->getArg(ArgNum);
2139 if (Arg->isTypeDependent() || Arg->isValueDependent())
2140 return false;
2141
2142 // Check constant-ness first.
2143 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2144 return true;
2145
2146 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2147 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2148 // combined with ROUND_NO_EXC.
2149 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2150 Result == 8/*ROUND_NO_EXC*/ ||
2151 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2152 return false;
2153
2154 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2155 << Arg->getSourceRange();
2156}
2157
Craig Topperdf5beb22017-03-13 17:16:50 +00002158// Check if the gather/scatter scale is legal.
2159bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2160 CallExpr *TheCall) {
2161 unsigned ArgNum = 0;
2162 switch (BuiltinID) {
2163 default:
2164 return false;
2165 case X86::BI__builtin_ia32_gatherpfdpd:
2166 case X86::BI__builtin_ia32_gatherpfdps:
2167 case X86::BI__builtin_ia32_gatherpfqpd:
2168 case X86::BI__builtin_ia32_gatherpfqps:
2169 case X86::BI__builtin_ia32_scatterpfdpd:
2170 case X86::BI__builtin_ia32_scatterpfdps:
2171 case X86::BI__builtin_ia32_scatterpfqpd:
2172 case X86::BI__builtin_ia32_scatterpfqps:
2173 ArgNum = 3;
2174 break;
2175 case X86::BI__builtin_ia32_gatherd_pd:
2176 case X86::BI__builtin_ia32_gatherd_pd256:
2177 case X86::BI__builtin_ia32_gatherq_pd:
2178 case X86::BI__builtin_ia32_gatherq_pd256:
2179 case X86::BI__builtin_ia32_gatherd_ps:
2180 case X86::BI__builtin_ia32_gatherd_ps256:
2181 case X86::BI__builtin_ia32_gatherq_ps:
2182 case X86::BI__builtin_ia32_gatherq_ps256:
2183 case X86::BI__builtin_ia32_gatherd_q:
2184 case X86::BI__builtin_ia32_gatherd_q256:
2185 case X86::BI__builtin_ia32_gatherq_q:
2186 case X86::BI__builtin_ia32_gatherq_q256:
2187 case X86::BI__builtin_ia32_gatherd_d:
2188 case X86::BI__builtin_ia32_gatherd_d256:
2189 case X86::BI__builtin_ia32_gatherq_d:
2190 case X86::BI__builtin_ia32_gatherq_d256:
2191 case X86::BI__builtin_ia32_gather3div2df:
2192 case X86::BI__builtin_ia32_gather3div2di:
2193 case X86::BI__builtin_ia32_gather3div4df:
2194 case X86::BI__builtin_ia32_gather3div4di:
2195 case X86::BI__builtin_ia32_gather3div4sf:
2196 case X86::BI__builtin_ia32_gather3div4si:
2197 case X86::BI__builtin_ia32_gather3div8sf:
2198 case X86::BI__builtin_ia32_gather3div8si:
2199 case X86::BI__builtin_ia32_gather3siv2df:
2200 case X86::BI__builtin_ia32_gather3siv2di:
2201 case X86::BI__builtin_ia32_gather3siv4df:
2202 case X86::BI__builtin_ia32_gather3siv4di:
2203 case X86::BI__builtin_ia32_gather3siv4sf:
2204 case X86::BI__builtin_ia32_gather3siv4si:
2205 case X86::BI__builtin_ia32_gather3siv8sf:
2206 case X86::BI__builtin_ia32_gather3siv8si:
2207 case X86::BI__builtin_ia32_gathersiv8df:
2208 case X86::BI__builtin_ia32_gathersiv16sf:
2209 case X86::BI__builtin_ia32_gatherdiv8df:
2210 case X86::BI__builtin_ia32_gatherdiv16sf:
2211 case X86::BI__builtin_ia32_gathersiv8di:
2212 case X86::BI__builtin_ia32_gathersiv16si:
2213 case X86::BI__builtin_ia32_gatherdiv8di:
2214 case X86::BI__builtin_ia32_gatherdiv16si:
2215 case X86::BI__builtin_ia32_scatterdiv2df:
2216 case X86::BI__builtin_ia32_scatterdiv2di:
2217 case X86::BI__builtin_ia32_scatterdiv4df:
2218 case X86::BI__builtin_ia32_scatterdiv4di:
2219 case X86::BI__builtin_ia32_scatterdiv4sf:
2220 case X86::BI__builtin_ia32_scatterdiv4si:
2221 case X86::BI__builtin_ia32_scatterdiv8sf:
2222 case X86::BI__builtin_ia32_scatterdiv8si:
2223 case X86::BI__builtin_ia32_scattersiv2df:
2224 case X86::BI__builtin_ia32_scattersiv2di:
2225 case X86::BI__builtin_ia32_scattersiv4df:
2226 case X86::BI__builtin_ia32_scattersiv4di:
2227 case X86::BI__builtin_ia32_scattersiv4sf:
2228 case X86::BI__builtin_ia32_scattersiv4si:
2229 case X86::BI__builtin_ia32_scattersiv8sf:
2230 case X86::BI__builtin_ia32_scattersiv8si:
2231 case X86::BI__builtin_ia32_scattersiv8df:
2232 case X86::BI__builtin_ia32_scattersiv16sf:
2233 case X86::BI__builtin_ia32_scatterdiv8df:
2234 case X86::BI__builtin_ia32_scatterdiv16sf:
2235 case X86::BI__builtin_ia32_scattersiv8di:
2236 case X86::BI__builtin_ia32_scattersiv16si:
2237 case X86::BI__builtin_ia32_scatterdiv8di:
2238 case X86::BI__builtin_ia32_scatterdiv16si:
2239 ArgNum = 4;
2240 break;
2241 }
2242
2243 llvm::APSInt Result;
2244
2245 // We can't check the value of a dependent argument.
2246 Expr *Arg = TheCall->getArg(ArgNum);
2247 if (Arg->isTypeDependent() || Arg->isValueDependent())
2248 return false;
2249
2250 // Check constant-ness first.
2251 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2252 return true;
2253
2254 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2255 return false;
2256
2257 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2258 << Arg->getSourceRange();
2259}
2260
Craig Topperf0ddc892016-09-23 04:48:27 +00002261bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2262 if (BuiltinID == X86::BI__builtin_cpu_supports)
2263 return SemaBuiltinCpuSupports(*this, TheCall);
2264
Craig Topper699ae0c2017-08-10 20:28:30 +00002265 if (BuiltinID == X86::BI__builtin_cpu_is)
2266 return SemaBuiltinCpuIs(*this, TheCall);
2267
Craig Toppera7e253e2016-09-23 04:48:31 +00002268 // If the intrinsic has rounding or SAE make sure its valid.
2269 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2270 return true;
2271
Craig Topperdf5beb22017-03-13 17:16:50 +00002272 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2273 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2274 return true;
2275
Craig Topperf0ddc892016-09-23 04:48:27 +00002276 // For intrinsics which take an immediate value as part of the instruction,
2277 // range check them here.
2278 int i = 0, l = 0, u = 0;
2279 switch (BuiltinID) {
2280 default:
2281 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002282 case X86::BI_mm_prefetch:
Craig Topper170de4b2017-12-21 23:50:22 +00002283 i = 1; l = 0; u = 7;
Craig Topper39c87102016-05-18 03:18:12 +00002284 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002285 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002286 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2287 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2288 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2289 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002290 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002291 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002292 case X86::BI__builtin_ia32_vpermil2pd:
2293 case X86::BI__builtin_ia32_vpermil2pd256:
2294 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002295 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002296 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002297 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002298 case X86::BI__builtin_ia32_cmpb128_mask:
2299 case X86::BI__builtin_ia32_cmpw128_mask:
2300 case X86::BI__builtin_ia32_cmpd128_mask:
2301 case X86::BI__builtin_ia32_cmpq128_mask:
2302 case X86::BI__builtin_ia32_cmpb256_mask:
2303 case X86::BI__builtin_ia32_cmpw256_mask:
2304 case X86::BI__builtin_ia32_cmpd256_mask:
2305 case X86::BI__builtin_ia32_cmpq256_mask:
2306 case X86::BI__builtin_ia32_cmpb512_mask:
2307 case X86::BI__builtin_ia32_cmpw512_mask:
2308 case X86::BI__builtin_ia32_cmpd512_mask:
2309 case X86::BI__builtin_ia32_cmpq512_mask:
2310 case X86::BI__builtin_ia32_ucmpb128_mask:
2311 case X86::BI__builtin_ia32_ucmpw128_mask:
2312 case X86::BI__builtin_ia32_ucmpd128_mask:
2313 case X86::BI__builtin_ia32_ucmpq128_mask:
2314 case X86::BI__builtin_ia32_ucmpb256_mask:
2315 case X86::BI__builtin_ia32_ucmpw256_mask:
2316 case X86::BI__builtin_ia32_ucmpd256_mask:
2317 case X86::BI__builtin_ia32_ucmpq256_mask:
2318 case X86::BI__builtin_ia32_ucmpb512_mask:
2319 case X86::BI__builtin_ia32_ucmpw512_mask:
2320 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002321 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002322 case X86::BI__builtin_ia32_vpcomub:
2323 case X86::BI__builtin_ia32_vpcomuw:
2324 case X86::BI__builtin_ia32_vpcomud:
2325 case X86::BI__builtin_ia32_vpcomuq:
2326 case X86::BI__builtin_ia32_vpcomb:
2327 case X86::BI__builtin_ia32_vpcomw:
2328 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002329 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002330 i = 2; l = 0; u = 7;
2331 break;
2332 case X86::BI__builtin_ia32_roundps:
2333 case X86::BI__builtin_ia32_roundpd:
2334 case X86::BI__builtin_ia32_roundps256:
2335 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002336 i = 1; l = 0; u = 15;
2337 break;
2338 case X86::BI__builtin_ia32_roundss:
2339 case X86::BI__builtin_ia32_roundsd:
2340 case X86::BI__builtin_ia32_rangepd128_mask:
2341 case X86::BI__builtin_ia32_rangepd256_mask:
2342 case X86::BI__builtin_ia32_rangepd512_mask:
2343 case X86::BI__builtin_ia32_rangeps128_mask:
2344 case X86::BI__builtin_ia32_rangeps256_mask:
2345 case X86::BI__builtin_ia32_rangeps512_mask:
2346 case X86::BI__builtin_ia32_getmantsd_round_mask:
2347 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002348 i = 2; l = 0; u = 15;
2349 break;
2350 case X86::BI__builtin_ia32_cmpps:
2351 case X86::BI__builtin_ia32_cmpss:
2352 case X86::BI__builtin_ia32_cmppd:
2353 case X86::BI__builtin_ia32_cmpsd:
2354 case X86::BI__builtin_ia32_cmpps256:
2355 case X86::BI__builtin_ia32_cmppd256:
2356 case X86::BI__builtin_ia32_cmpps128_mask:
2357 case X86::BI__builtin_ia32_cmppd128_mask:
2358 case X86::BI__builtin_ia32_cmpps256_mask:
2359 case X86::BI__builtin_ia32_cmppd256_mask:
2360 case X86::BI__builtin_ia32_cmpps512_mask:
2361 case X86::BI__builtin_ia32_cmppd512_mask:
2362 case X86::BI__builtin_ia32_cmpsd_mask:
2363 case X86::BI__builtin_ia32_cmpss_mask:
2364 i = 2; l = 0; u = 31;
2365 break;
Craig Topper39c87102016-05-18 03:18:12 +00002366 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002367 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002368 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002369 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2370 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002371 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2372 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2373 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2374 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2375 case X86::BI__builtin_ia32_rndscaleps_mask:
2376 case X86::BI__builtin_ia32_rndscalepd_mask:
2377 case X86::BI__builtin_ia32_reducepd128_mask:
2378 case X86::BI__builtin_ia32_reducepd256_mask:
2379 case X86::BI__builtin_ia32_reducepd512_mask:
2380 case X86::BI__builtin_ia32_reduceps128_mask:
2381 case X86::BI__builtin_ia32_reduceps256_mask:
2382 case X86::BI__builtin_ia32_reduceps512_mask:
2383 case X86::BI__builtin_ia32_prold512_mask:
2384 case X86::BI__builtin_ia32_prolq512_mask:
2385 case X86::BI__builtin_ia32_prold128_mask:
2386 case X86::BI__builtin_ia32_prold256_mask:
2387 case X86::BI__builtin_ia32_prolq128_mask:
2388 case X86::BI__builtin_ia32_prolq256_mask:
2389 case X86::BI__builtin_ia32_prord128_mask:
2390 case X86::BI__builtin_ia32_prord256_mask:
2391 case X86::BI__builtin_ia32_prorq128_mask:
2392 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002393 case X86::BI__builtin_ia32_fpclasspd128_mask:
2394 case X86::BI__builtin_ia32_fpclasspd256_mask:
2395 case X86::BI__builtin_ia32_fpclassps128_mask:
2396 case X86::BI__builtin_ia32_fpclassps256_mask:
2397 case X86::BI__builtin_ia32_fpclassps512_mask:
2398 case X86::BI__builtin_ia32_fpclasspd512_mask:
2399 case X86::BI__builtin_ia32_fpclasssd_mask:
2400 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002401 i = 1; l = 0; u = 255;
2402 break;
Craig Topper39c87102016-05-18 03:18:12 +00002403 case X86::BI__builtin_ia32_palignr128:
2404 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002405 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002406 case X86::BI__builtin_ia32_vcomisd:
2407 case X86::BI__builtin_ia32_vcomiss:
2408 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2409 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2410 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2411 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002412 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2413 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2414 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002415 case X86::BI__builtin_ia32_vpshldd128_mask:
2416 case X86::BI__builtin_ia32_vpshldd256_mask:
2417 case X86::BI__builtin_ia32_vpshldd512_mask:
2418 case X86::BI__builtin_ia32_vpshldq128_mask:
2419 case X86::BI__builtin_ia32_vpshldq256_mask:
2420 case X86::BI__builtin_ia32_vpshldq512_mask:
2421 case X86::BI__builtin_ia32_vpshldw128_mask:
2422 case X86::BI__builtin_ia32_vpshldw256_mask:
2423 case X86::BI__builtin_ia32_vpshldw512_mask:
2424 case X86::BI__builtin_ia32_vpshrdd128_mask:
2425 case X86::BI__builtin_ia32_vpshrdd256_mask:
2426 case X86::BI__builtin_ia32_vpshrdd512_mask:
2427 case X86::BI__builtin_ia32_vpshrdq128_mask:
2428 case X86::BI__builtin_ia32_vpshrdq256_mask:
2429 case X86::BI__builtin_ia32_vpshrdq512_mask:
2430 case X86::BI__builtin_ia32_vpshrdw128_mask:
2431 case X86::BI__builtin_ia32_vpshrdw256_mask:
2432 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002433 i = 2; l = 0; u = 255;
2434 break;
2435 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2436 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2437 case X86::BI__builtin_ia32_fixupimmps512_mask:
2438 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2439 case X86::BI__builtin_ia32_fixupimmsd_mask:
2440 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2441 case X86::BI__builtin_ia32_fixupimmss_mask:
2442 case X86::BI__builtin_ia32_fixupimmss_maskz:
2443 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2444 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2445 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2446 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2447 case X86::BI__builtin_ia32_fixupimmps128_mask:
2448 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2449 case X86::BI__builtin_ia32_fixupimmps256_mask:
2450 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2451 case X86::BI__builtin_ia32_pternlogd512_mask:
2452 case X86::BI__builtin_ia32_pternlogd512_maskz:
2453 case X86::BI__builtin_ia32_pternlogq512_mask:
2454 case X86::BI__builtin_ia32_pternlogq512_maskz:
2455 case X86::BI__builtin_ia32_pternlogd128_mask:
2456 case X86::BI__builtin_ia32_pternlogd128_maskz:
2457 case X86::BI__builtin_ia32_pternlogd256_mask:
2458 case X86::BI__builtin_ia32_pternlogd256_maskz:
2459 case X86::BI__builtin_ia32_pternlogq128_mask:
2460 case X86::BI__builtin_ia32_pternlogq128_maskz:
2461 case X86::BI__builtin_ia32_pternlogq256_mask:
2462 case X86::BI__builtin_ia32_pternlogq256_maskz:
2463 i = 3; l = 0; u = 255;
2464 break;
Craig Topper9625db02017-03-12 22:19:10 +00002465 case X86::BI__builtin_ia32_gatherpfdpd:
2466 case X86::BI__builtin_ia32_gatherpfdps:
2467 case X86::BI__builtin_ia32_gatherpfqpd:
2468 case X86::BI__builtin_ia32_gatherpfqps:
2469 case X86::BI__builtin_ia32_scatterpfdpd:
2470 case X86::BI__builtin_ia32_scatterpfdps:
2471 case X86::BI__builtin_ia32_scatterpfqpd:
2472 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002473 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002474 break;
Craig Topper39c87102016-05-18 03:18:12 +00002475 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2476 case X86::BI__builtin_ia32_rndscaless_round_mask:
2477 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002478 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002479 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002480 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002481}
2482
Richard Smith55ce3522012-06-25 20:30:08 +00002483/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2484/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2485/// Returns true when the format fits the function and the FormatStringInfo has
2486/// been populated.
2487bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2488 FormatStringInfo *FSI) {
2489 FSI->HasVAListArg = Format->getFirstArg() == 0;
2490 FSI->FormatIdx = Format->getFormatIdx() - 1;
2491 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002492
Richard Smith55ce3522012-06-25 20:30:08 +00002493 // The way the format attribute works in GCC, the implicit this argument
2494 // of member functions is counted. However, it doesn't appear in our own
2495 // lists, so decrement format_idx in that case.
2496 if (IsCXXMember) {
2497 if(FSI->FormatIdx == 0)
2498 return false;
2499 --FSI->FormatIdx;
2500 if (FSI->FirstDataArg != 0)
2501 --FSI->FirstDataArg;
2502 }
2503 return true;
2504}
Mike Stump11289f42009-09-09 15:08:12 +00002505
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002506/// Checks if a the given expression evaluates to null.
2507///
2508/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002509static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002510 // If the expression has non-null type, it doesn't evaluate to null.
2511 if (auto nullability
2512 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2513 if (*nullability == NullabilityKind::NonNull)
2514 return false;
2515 }
2516
Ted Kremeneka146db32014-01-17 06:24:47 +00002517 // As a special case, transparent unions initialized with zero are
2518 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002519 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002520 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2521 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002522 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002523 if (const InitListExpr *ILE =
2524 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002525 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002526 }
2527
2528 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002529 return (!Expr->isValueDependent() &&
2530 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2531 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002532}
2533
2534static void CheckNonNullArgument(Sema &S,
2535 const Expr *ArgExpr,
2536 SourceLocation CallSiteLoc) {
2537 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002538 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2539 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002540}
2541
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002542bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2543 FormatStringInfo FSI;
2544 if ((GetFormatStringType(Format) == FST_NSString) &&
2545 getFormatStringInfo(Format, false, &FSI)) {
2546 Idx = FSI.FormatIdx;
2547 return true;
2548 }
2549 return false;
2550}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002551
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002552/// \brief Diagnose use of %s directive in an NSString which is being passed
2553/// as formatting string to formatting method.
2554static void
2555DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2556 const NamedDecl *FDecl,
2557 Expr **Args,
2558 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002559 unsigned Idx = 0;
2560 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002561 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2562 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002563 Idx = 2;
2564 Format = true;
2565 }
2566 else
2567 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2568 if (S.GetFormatNSStringIdx(I, Idx)) {
2569 Format = true;
2570 break;
2571 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002572 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002573 if (!Format || NumArgs <= Idx)
2574 return;
2575 const Expr *FormatExpr = Args[Idx];
2576 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2577 FormatExpr = CSCE->getSubExpr();
2578 const StringLiteral *FormatString;
2579 if (const ObjCStringLiteral *OSL =
2580 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2581 FormatString = OSL->getString();
2582 else
2583 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2584 if (!FormatString)
2585 return;
2586 if (S.FormatStringHasSArg(FormatString)) {
2587 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2588 << "%s" << 1 << 1;
2589 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2590 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002591 }
2592}
2593
Douglas Gregorb4866e82015-06-19 18:13:19 +00002594/// Determine whether the given type has a non-null nullability annotation.
2595static bool isNonNullType(ASTContext &ctx, QualType type) {
2596 if (auto nullability = type->getNullability(ctx))
2597 return *nullability == NullabilityKind::NonNull;
2598
2599 return false;
2600}
2601
Ted Kremenek2bc73332014-01-17 06:24:43 +00002602static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002603 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002604 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002605 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002606 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002607 assert((FDecl || Proto) && "Need a function declaration or prototype");
2608
Ted Kremenek9aedc152014-01-17 06:24:56 +00002609 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002610 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002611 if (FDecl) {
2612 // Handle the nonnull attribute on the function/method declaration itself.
2613 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2614 if (!NonNull->args_size()) {
2615 // Easy case: all pointer arguments are nonnull.
2616 for (const auto *Arg : Args)
2617 if (S.isValidPointerAttrType(Arg->getType()))
2618 CheckNonNullArgument(S, Arg, CallSiteLoc);
2619 return;
2620 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002621
Douglas Gregorb4866e82015-06-19 18:13:19 +00002622 for (unsigned Val : NonNull->args()) {
2623 if (Val >= Args.size())
2624 continue;
2625 if (NonNullArgs.empty())
2626 NonNullArgs.resize(Args.size());
2627 NonNullArgs.set(Val);
2628 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002629 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002630 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002631
Douglas Gregorb4866e82015-06-19 18:13:19 +00002632 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2633 // Handle the nonnull attribute on the parameters of the
2634 // function/method.
2635 ArrayRef<ParmVarDecl*> parms;
2636 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2637 parms = FD->parameters();
2638 else
2639 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2640
2641 unsigned ParamIndex = 0;
2642 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2643 I != E; ++I, ++ParamIndex) {
2644 const ParmVarDecl *PVD = *I;
2645 if (PVD->hasAttr<NonNullAttr>() ||
2646 isNonNullType(S.Context, PVD->getType())) {
2647 if (NonNullArgs.empty())
2648 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002649
Douglas Gregorb4866e82015-06-19 18:13:19 +00002650 NonNullArgs.set(ParamIndex);
2651 }
2652 }
2653 } else {
2654 // If we have a non-function, non-method declaration but no
2655 // function prototype, try to dig out the function prototype.
2656 if (!Proto) {
2657 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2658 QualType type = VD->getType().getNonReferenceType();
2659 if (auto pointerType = type->getAs<PointerType>())
2660 type = pointerType->getPointeeType();
2661 else if (auto blockType = type->getAs<BlockPointerType>())
2662 type = blockType->getPointeeType();
2663 // FIXME: data member pointers?
2664
2665 // Dig out the function prototype, if there is one.
2666 Proto = type->getAs<FunctionProtoType>();
2667 }
2668 }
2669
2670 // Fill in non-null argument information from the nullability
2671 // information on the parameter types (if we have them).
2672 if (Proto) {
2673 unsigned Index = 0;
2674 for (auto paramType : Proto->getParamTypes()) {
2675 if (isNonNullType(S.Context, paramType)) {
2676 if (NonNullArgs.empty())
2677 NonNullArgs.resize(Args.size());
2678
2679 NonNullArgs.set(Index);
2680 }
2681
2682 ++Index;
2683 }
2684 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002685 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002686
Douglas Gregorb4866e82015-06-19 18:13:19 +00002687 // Check for non-null arguments.
2688 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2689 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002690 if (NonNullArgs[ArgIndex])
2691 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002692 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002693}
2694
Richard Smith55ce3522012-06-25 20:30:08 +00002695/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002696/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2697/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002698void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002699 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2700 bool IsMemberFunction, SourceLocation Loc,
2701 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002702 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002703 if (CurContext->isDependentContext())
2704 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002705
Ted Kremenekb8176da2010-09-09 04:33:05 +00002706 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002707 llvm::SmallBitVector CheckedVarArgs;
2708 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002709 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002710 // Only create vector if there are format attributes.
2711 CheckedVarArgs.resize(Args.size());
2712
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002713 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002714 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002715 }
Richard Smithd7293d72013-08-05 18:49:43 +00002716 }
Richard Smith55ce3522012-06-25 20:30:08 +00002717
2718 // Refuse POD arguments that weren't caught by the format string
2719 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002720 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2721 if (CallType != VariadicDoesNotApply &&
2722 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002723 unsigned NumParams = Proto ? Proto->getNumParams()
2724 : FDecl && isa<FunctionDecl>(FDecl)
2725 ? cast<FunctionDecl>(FDecl)->getNumParams()
2726 : FDecl && isa<ObjCMethodDecl>(FDecl)
2727 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2728 : 0;
2729
Alp Toker9cacbab2014-01-20 20:26:09 +00002730 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002731 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002732 if (const Expr *Arg = Args[ArgIdx]) {
2733 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2734 checkVariadicArgument(Arg, CallType);
2735 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002736 }
Richard Smithd7293d72013-08-05 18:49:43 +00002737 }
Mike Stump11289f42009-09-09 15:08:12 +00002738
Douglas Gregorb4866e82015-06-19 18:13:19 +00002739 if (FDecl || Proto) {
2740 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002741
Richard Trieu41bc0992013-06-22 00:20:41 +00002742 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002743 if (FDecl) {
2744 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00002745 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002746 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002747 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002748
2749 if (FD)
2750 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002751}
2752
2753/// CheckConstructorCall - Check a constructor call for correctness and safety
2754/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002755void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2756 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002757 const FunctionProtoType *Proto,
2758 SourceLocation Loc) {
2759 VariadicCallType CallType =
2760 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002761 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2762 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002763}
2764
2765/// CheckFunctionCall - Check a direct function call for various correctness
2766/// and safety properties not strictly enforced by the C type system.
2767bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2768 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002769 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2770 isa<CXXMethodDecl>(FDecl);
2771 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2772 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002773 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2774 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002775 Expr** Args = TheCall->getArgs();
2776 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002777
2778 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002779 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002780 // If this is a call to a member operator, hide the first argument
2781 // from checkCall.
2782 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002783 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002784 ++Args;
2785 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002786 } else if (IsMemberFunction)
2787 ImplicitThis =
2788 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2789
2790 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002791 IsMemberFunction, TheCall->getRParenLoc(),
2792 TheCall->getCallee()->getSourceRange(), CallType);
2793
2794 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2795 // None of the checks below are needed for functions that don't have
2796 // simple names (e.g., C++ conversion functions).
2797 if (!FnInfo)
2798 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002799
Richard Trieua7f30b12016-12-06 01:42:28 +00002800 CheckAbsoluteValueFunction(TheCall, FDecl);
2801 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002802
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002803 if (getLangOpts().ObjC1)
2804 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002805
Anna Zaks22122702012-01-17 00:37:07 +00002806 unsigned CMId = FDecl->getMemoryFunctionKind();
2807 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002808 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002809
Anna Zaks201d4892012-01-13 21:52:01 +00002810 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002811 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002812 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002813 else if (CMId == Builtin::BIstrncat)
2814 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002815 else
Anna Zaks22122702012-01-17 00:37:07 +00002816 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002817
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002818 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002819}
2820
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002821bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002822 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002823 VariadicCallType CallType =
2824 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002825
George Burgess IVce6284b2017-01-28 02:19:40 +00002826 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2827 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002828 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002829
2830 return false;
2831}
2832
Richard Trieu664c4c62013-06-20 21:03:13 +00002833bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2834 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002835 QualType Ty;
2836 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002837 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002838 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002839 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002840 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002841 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002842
Douglas Gregorb4866e82015-06-19 18:13:19 +00002843 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2844 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002845 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002846
Richard Trieu664c4c62013-06-20 21:03:13 +00002847 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002848 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002849 CallType = VariadicDoesNotApply;
2850 } else if (Ty->isBlockPointerType()) {
2851 CallType = VariadicBlock;
2852 } else { // Ty->isFunctionPointerType()
2853 CallType = VariadicFunction;
2854 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002855
George Burgess IVce6284b2017-01-28 02:19:40 +00002856 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002857 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2858 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002859 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002860
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002861 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002862}
2863
Richard Trieu41bc0992013-06-22 00:20:41 +00002864/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2865/// such as function pointers returned from functions.
2866bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002867 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002868 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002869 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002870 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002871 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002872 TheCall->getCallee()->getSourceRange(), CallType);
2873
2874 return false;
2875}
2876
Tim Northovere94a34c2014-03-11 10:49:14 +00002877static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002878 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002879 return false;
2880
JF Bastiendda2cb12016-04-18 18:01:49 +00002881 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002882 switch (Op) {
2883 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002884 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002885 llvm_unreachable("There is no ordering argument for an init");
2886
2887 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002888 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002889 case AtomicExpr::AO__atomic_load_n:
2890 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002891 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2892 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002893
2894 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002895 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002896 case AtomicExpr::AO__atomic_store:
2897 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002898 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2899 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2900 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002901
2902 default:
2903 return true;
2904 }
2905}
2906
Richard Smithfeea8832012-04-12 05:08:17 +00002907ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2908 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002909 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2910 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002911
Yaxun Liu39195062017-08-04 18:16:31 +00002912 // All the non-OpenCL operations take one of the following forms.
2913 // The OpenCL operations take the __c11 forms with one extra argument for
2914 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002915 enum {
2916 // C __c11_atomic_init(A *, C)
2917 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002918
Richard Smithfeea8832012-04-12 05:08:17 +00002919 // C __c11_atomic_load(A *, int)
2920 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002921
Richard Smithfeea8832012-04-12 05:08:17 +00002922 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002923 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002924
Eric Fiselier8d662442016-03-30 23:39:56 +00002925 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002926 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002927
Richard Smithfeea8832012-04-12 05:08:17 +00002928 // C __c11_atomic_add(A *, M, int)
2929 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002930
Richard Smithfeea8832012-04-12 05:08:17 +00002931 // C __atomic_exchange_n(A *, CP, int)
2932 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002933
Richard Smithfeea8832012-04-12 05:08:17 +00002934 // void __atomic_exchange(A *, C *, CP, int)
2935 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002936
Richard Smithfeea8832012-04-12 05:08:17 +00002937 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2938 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002939
Richard Smithfeea8832012-04-12 05:08:17 +00002940 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2941 GNUCmpXchg
2942 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002943
Yaxun Liu39195062017-08-04 18:16:31 +00002944 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002945 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2946 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002947 // where:
2948 // C is an appropriate type,
2949 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2950 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2951 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2952 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002953
Yaxun Liu39195062017-08-04 18:16:31 +00002954 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2955 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2956 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00002957 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2958 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2959 AtomicExpr::AO__atomic_load,
2960 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00002961 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2962 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2963 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2964 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2965 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00002966 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2967 Op == AtomicExpr::AO__atomic_store_n ||
2968 Op == AtomicExpr::AO__atomic_exchange_n ||
2969 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2970 bool IsAddSub = false;
2971
2972 switch (Op) {
2973 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002974 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00002975 Form = Init;
2976 break;
2977
2978 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002979 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00002980 case AtomicExpr::AO__atomic_load_n:
2981 Form = Load;
2982 break;
2983
Richard Smithfeea8832012-04-12 05:08:17 +00002984 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002985 Form = LoadCopy;
2986 break;
2987
2988 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002989 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002990 case AtomicExpr::AO__atomic_store:
2991 case AtomicExpr::AO__atomic_store_n:
2992 Form = Copy;
2993 break;
2994
2995 case AtomicExpr::AO__c11_atomic_fetch_add:
2996 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00002997 case AtomicExpr::AO__opencl_atomic_fetch_add:
2998 case AtomicExpr::AO__opencl_atomic_fetch_sub:
2999 case AtomicExpr::AO__opencl_atomic_fetch_min:
3000 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003001 case AtomicExpr::AO__atomic_fetch_add:
3002 case AtomicExpr::AO__atomic_fetch_sub:
3003 case AtomicExpr::AO__atomic_add_fetch:
3004 case AtomicExpr::AO__atomic_sub_fetch:
3005 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003006 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003007 case AtomicExpr::AO__c11_atomic_fetch_and:
3008 case AtomicExpr::AO__c11_atomic_fetch_or:
3009 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003010 case AtomicExpr::AO__opencl_atomic_fetch_and:
3011 case AtomicExpr::AO__opencl_atomic_fetch_or:
3012 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003013 case AtomicExpr::AO__atomic_fetch_and:
3014 case AtomicExpr::AO__atomic_fetch_or:
3015 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003016 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003017 case AtomicExpr::AO__atomic_and_fetch:
3018 case AtomicExpr::AO__atomic_or_fetch:
3019 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003020 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003021 Form = Arithmetic;
3022 break;
3023
3024 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003025 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003026 case AtomicExpr::AO__atomic_exchange_n:
3027 Form = Xchg;
3028 break;
3029
3030 case AtomicExpr::AO__atomic_exchange:
3031 Form = GNUXchg;
3032 break;
3033
3034 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3035 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003036 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3037 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003038 Form = C11CmpXchg;
3039 break;
3040
3041 case AtomicExpr::AO__atomic_compare_exchange:
3042 case AtomicExpr::AO__atomic_compare_exchange_n:
3043 Form = GNUCmpXchg;
3044 break;
3045 }
3046
Yaxun Liu39195062017-08-04 18:16:31 +00003047 unsigned AdjustedNumArgs = NumArgs[Form];
3048 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3049 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003050 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003051 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003052 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003053 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003054 << TheCall->getCallee()->getSourceRange();
3055 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003056 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3057 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003058 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003059 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003060 << TheCall->getCallee()->getSourceRange();
3061 return ExprError();
3062 }
3063
Richard Smithfeea8832012-04-12 05:08:17 +00003064 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003065 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003066 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3067 if (ConvertedPtr.isInvalid())
3068 return ExprError();
3069
3070 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003071 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3072 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003073 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003074 << Ptr->getType() << Ptr->getSourceRange();
3075 return ExprError();
3076 }
3077
Richard Smithfeea8832012-04-12 05:08:17 +00003078 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3079 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3080 QualType ValType = AtomTy; // 'C'
3081 if (IsC11) {
3082 if (!AtomTy->isAtomicType()) {
3083 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3084 << Ptr->getType() << Ptr->getSourceRange();
3085 return ExprError();
3086 }
Yaxun Liu39195062017-08-04 18:16:31 +00003087 if (AtomTy.isConstQualified() ||
3088 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003089 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003090 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3091 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003092 return ExprError();
3093 }
Richard Smithfeea8832012-04-12 05:08:17 +00003094 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003095 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003096 if (ValType.isConstQualified()) {
3097 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3098 << Ptr->getType() << Ptr->getSourceRange();
3099 return ExprError();
3100 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003101 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003102
Richard Smithfeea8832012-04-12 05:08:17 +00003103 // For an arithmetic operation, the implied arithmetic must be well-formed.
3104 if (Form == Arithmetic) {
3105 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3106 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3107 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3108 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3109 return ExprError();
3110 }
3111 if (!IsAddSub && !ValType->isIntegerType()) {
3112 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3113 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3114 return ExprError();
3115 }
David Majnemere85cff82015-01-28 05:48:06 +00003116 if (IsC11 && ValType->isPointerType() &&
3117 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3118 diag::err_incomplete_type)) {
3119 return ExprError();
3120 }
Richard Smithfeea8832012-04-12 05:08:17 +00003121 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3122 // For __atomic_*_n operations, the value type must be a scalar integral or
3123 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003124 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003125 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3126 return ExprError();
3127 }
3128
Eli Friedmanaa769812013-09-11 03:49:34 +00003129 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3130 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003131 // For GNU atomics, require a trivially-copyable type. This is not part of
3132 // the GNU atomics specification, but we enforce it for sanity.
3133 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003134 << Ptr->getType() << Ptr->getSourceRange();
3135 return ExprError();
3136 }
3137
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003138 switch (ValType.getObjCLifetime()) {
3139 case Qualifiers::OCL_None:
3140 case Qualifiers::OCL_ExplicitNone:
3141 // okay
3142 break;
3143
3144 case Qualifiers::OCL_Weak:
3145 case Qualifiers::OCL_Strong:
3146 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003147 // FIXME: Can this happen? By this point, ValType should be known
3148 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003149 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3150 << ValType << Ptr->getSourceRange();
3151 return ExprError();
3152 }
3153
David Majnemerc6eb6502015-06-03 00:26:35 +00003154 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3155 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003156 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003157 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003158 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003159 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003160 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3161 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003162 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003163 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003164 ResultType = Context.BoolTy;
3165
Richard Smithfeea8832012-04-12 05:08:17 +00003166 // The type of a parameter passed 'by value'. In the GNU atomics, such
3167 // arguments are actually passed as pointers.
3168 QualType ByValType = ValType; // 'CP'
3169 if (!IsC11 && !IsN)
3170 ByValType = Ptr->getType();
3171
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003172 // The first argument --- the pointer --- has a fixed type; we
3173 // deduce the types of the rest of the arguments accordingly. Walk
3174 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003175 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003176 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003177 if (i < NumVals[Form] + 1) {
3178 switch (i) {
3179 case 1:
3180 // The second argument is the non-atomic operand. For arithmetic, this
3181 // is always passed by value, and for a compare_exchange it is always
3182 // passed by address. For the rest, GNU uses by-address and C11 uses
3183 // by-value.
3184 assert(Form != Load);
3185 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3186 Ty = ValType;
3187 else if (Form == Copy || Form == Xchg)
3188 Ty = ByValType;
3189 else if (Form == Arithmetic)
3190 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003191 else {
3192 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003193 // Treat this argument as _Nonnull as we want to show a warning if
3194 // NULL is passed into it.
3195 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003196 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003197 // Keep address space of non-atomic pointer type.
3198 if (const PointerType *PtrTy =
3199 ValArg->getType()->getAs<PointerType>()) {
3200 AS = PtrTy->getPointeeType().getAddressSpace();
3201 }
3202 Ty = Context.getPointerType(
3203 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3204 }
Richard Smithfeea8832012-04-12 05:08:17 +00003205 break;
3206 case 2:
3207 // The third argument to compare_exchange / GNU exchange is a
3208 // (pointer to a) desired value.
3209 Ty = ByValType;
3210 break;
3211 case 3:
3212 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3213 Ty = Context.BoolTy;
3214 break;
3215 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003216 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003217 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003218 Ty = Context.IntTy;
3219 }
Richard Smithfeea8832012-04-12 05:08:17 +00003220
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003221 InitializedEntity Entity =
3222 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003223 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003224 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3225 if (Arg.isInvalid())
3226 return true;
3227 TheCall->setArg(i, Arg.get());
3228 }
3229
Richard Smithfeea8832012-04-12 05:08:17 +00003230 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003231 SmallVector<Expr*, 5> SubExprs;
3232 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003233 switch (Form) {
3234 case Init:
3235 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003236 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003237 break;
3238 case Load:
3239 SubExprs.push_back(TheCall->getArg(1)); // Order
3240 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003241 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003242 case Copy:
3243 case Arithmetic:
3244 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003245 SubExprs.push_back(TheCall->getArg(2)); // Order
3246 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003247 break;
3248 case GNUXchg:
3249 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3250 SubExprs.push_back(TheCall->getArg(3)); // Order
3251 SubExprs.push_back(TheCall->getArg(1)); // Val1
3252 SubExprs.push_back(TheCall->getArg(2)); // Val2
3253 break;
3254 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003255 SubExprs.push_back(TheCall->getArg(3)); // Order
3256 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003257 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003258 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003259 break;
3260 case GNUCmpXchg:
3261 SubExprs.push_back(TheCall->getArg(4)); // Order
3262 SubExprs.push_back(TheCall->getArg(1)); // Val1
3263 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3264 SubExprs.push_back(TheCall->getArg(2)); // Val2
3265 SubExprs.push_back(TheCall->getArg(3)); // Weak
3266 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003267 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003268
3269 if (SubExprs.size() >= 2 && Form != Init) {
3270 llvm::APSInt Result(32);
3271 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3272 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003273 Diag(SubExprs[1]->getLocStart(),
3274 diag::warn_atomic_op_has_invalid_memory_order)
3275 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003276 }
3277
Yaxun Liu30d652a2017-08-15 16:02:49 +00003278 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3279 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3280 llvm::APSInt Result(32);
3281 if (Scope->isIntegerConstantExpr(Result, Context) &&
3282 !ScopeModel->isValid(Result.getZExtValue())) {
3283 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3284 << Scope->getSourceRange();
3285 }
3286 SubExprs.push_back(Scope);
3287 }
3288
Fariborz Jahanian615de762013-05-28 17:37:39 +00003289 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3290 SubExprs, ResultType, Op,
3291 TheCall->getRParenLoc());
3292
3293 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003294 Op == AtomicExpr::AO__c11_atomic_store ||
3295 Op == AtomicExpr::AO__opencl_atomic_load ||
3296 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003297 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003298 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3299 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3300 Op == AtomicExpr::AO__opencl_atomic_load)
3301 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003302
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003303 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003304}
3305
John McCall29ad95b2011-08-27 01:09:30 +00003306/// checkBuiltinArgument - Given a call to a builtin function, perform
3307/// normal type-checking on the given argument, updating the call in
3308/// place. This is useful when a builtin function requires custom
3309/// type-checking for some of its arguments but not necessarily all of
3310/// them.
3311///
3312/// Returns true on error.
3313static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3314 FunctionDecl *Fn = E->getDirectCallee();
3315 assert(Fn && "builtin call without direct callee!");
3316
3317 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3318 InitializedEntity Entity =
3319 InitializedEntity::InitializeParameter(S.Context, Param);
3320
3321 ExprResult Arg = E->getArg(0);
3322 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3323 if (Arg.isInvalid())
3324 return true;
3325
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003326 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003327 return false;
3328}
3329
Chris Lattnerdc046542009-05-08 06:58:22 +00003330/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3331/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3332/// type of its first argument. The main ActOnCallExpr routines have already
3333/// promoted the types of arguments because all of these calls are prototyped as
3334/// void(...).
3335///
3336/// This function goes through and does final semantic checking for these
3337/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003338ExprResult
3339Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003340 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003341 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3342 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3343
3344 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003345 if (TheCall->getNumArgs() < 1) {
3346 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3347 << 0 << 1 << TheCall->getNumArgs()
3348 << TheCall->getCallee()->getSourceRange();
3349 return ExprError();
3350 }
Mike Stump11289f42009-09-09 15:08:12 +00003351
Chris Lattnerdc046542009-05-08 06:58:22 +00003352 // Inspect the first argument of the atomic builtin. This should always be
3353 // a pointer type, whose element is an integral scalar or pointer type.
3354 // Because it is a pointer type, we don't have to worry about any implicit
3355 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003356 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003357 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003358 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3359 if (FirstArgResult.isInvalid())
3360 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003361 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003362 TheCall->setArg(0, FirstArg);
3363
John McCall31168b02011-06-15 23:02:42 +00003364 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3365 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003366 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3367 << FirstArg->getType() << FirstArg->getSourceRange();
3368 return ExprError();
3369 }
Mike Stump11289f42009-09-09 15:08:12 +00003370
John McCall31168b02011-06-15 23:02:42 +00003371 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003372 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003373 !ValType->isBlockPointerType()) {
3374 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3375 << FirstArg->getType() << FirstArg->getSourceRange();
3376 return ExprError();
3377 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003378
John McCall31168b02011-06-15 23:02:42 +00003379 switch (ValType.getObjCLifetime()) {
3380 case Qualifiers::OCL_None:
3381 case Qualifiers::OCL_ExplicitNone:
3382 // okay
3383 break;
3384
3385 case Qualifiers::OCL_Weak:
3386 case Qualifiers::OCL_Strong:
3387 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003388 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003389 << ValType << FirstArg->getSourceRange();
3390 return ExprError();
3391 }
3392
John McCallb50451a2011-10-05 07:41:44 +00003393 // Strip any qualifiers off ValType.
3394 ValType = ValType.getUnqualifiedType();
3395
Chandler Carruth3973af72010-07-18 20:54:12 +00003396 // The majority of builtins return a value, but a few have special return
3397 // types, so allow them to override appropriately below.
3398 QualType ResultType = ValType;
3399
Chris Lattnerdc046542009-05-08 06:58:22 +00003400 // We need to figure out which concrete builtin this maps onto. For example,
3401 // __sync_fetch_and_add with a 2 byte object turns into
3402 // __sync_fetch_and_add_2.
3403#define BUILTIN_ROW(x) \
3404 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3405 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003406
Chris Lattnerdc046542009-05-08 06:58:22 +00003407 static const unsigned BuiltinIndices[][5] = {
3408 BUILTIN_ROW(__sync_fetch_and_add),
3409 BUILTIN_ROW(__sync_fetch_and_sub),
3410 BUILTIN_ROW(__sync_fetch_and_or),
3411 BUILTIN_ROW(__sync_fetch_and_and),
3412 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003413 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003414
Chris Lattnerdc046542009-05-08 06:58:22 +00003415 BUILTIN_ROW(__sync_add_and_fetch),
3416 BUILTIN_ROW(__sync_sub_and_fetch),
3417 BUILTIN_ROW(__sync_and_and_fetch),
3418 BUILTIN_ROW(__sync_or_and_fetch),
3419 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003420 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003421
Chris Lattnerdc046542009-05-08 06:58:22 +00003422 BUILTIN_ROW(__sync_val_compare_and_swap),
3423 BUILTIN_ROW(__sync_bool_compare_and_swap),
3424 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003425 BUILTIN_ROW(__sync_lock_release),
3426 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003427 };
Mike Stump11289f42009-09-09 15:08:12 +00003428#undef BUILTIN_ROW
3429
Chris Lattnerdc046542009-05-08 06:58:22 +00003430 // Determine the index of the size.
3431 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003432 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003433 case 1: SizeIndex = 0; break;
3434 case 2: SizeIndex = 1; break;
3435 case 4: SizeIndex = 2; break;
3436 case 8: SizeIndex = 3; break;
3437 case 16: SizeIndex = 4; break;
3438 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003439 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3440 << FirstArg->getType() << FirstArg->getSourceRange();
3441 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003442 }
Mike Stump11289f42009-09-09 15:08:12 +00003443
Chris Lattnerdc046542009-05-08 06:58:22 +00003444 // Each of these builtins has one pointer argument, followed by some number of
3445 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3446 // that we ignore. Find out which row of BuiltinIndices to read from as well
3447 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003448 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003449 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003450 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003451 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003452 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003453 case Builtin::BI__sync_fetch_and_add:
3454 case Builtin::BI__sync_fetch_and_add_1:
3455 case Builtin::BI__sync_fetch_and_add_2:
3456 case Builtin::BI__sync_fetch_and_add_4:
3457 case Builtin::BI__sync_fetch_and_add_8:
3458 case Builtin::BI__sync_fetch_and_add_16:
3459 BuiltinIndex = 0;
3460 break;
3461
3462 case Builtin::BI__sync_fetch_and_sub:
3463 case Builtin::BI__sync_fetch_and_sub_1:
3464 case Builtin::BI__sync_fetch_and_sub_2:
3465 case Builtin::BI__sync_fetch_and_sub_4:
3466 case Builtin::BI__sync_fetch_and_sub_8:
3467 case Builtin::BI__sync_fetch_and_sub_16:
3468 BuiltinIndex = 1;
3469 break;
3470
3471 case Builtin::BI__sync_fetch_and_or:
3472 case Builtin::BI__sync_fetch_and_or_1:
3473 case Builtin::BI__sync_fetch_and_or_2:
3474 case Builtin::BI__sync_fetch_and_or_4:
3475 case Builtin::BI__sync_fetch_and_or_8:
3476 case Builtin::BI__sync_fetch_and_or_16:
3477 BuiltinIndex = 2;
3478 break;
3479
3480 case Builtin::BI__sync_fetch_and_and:
3481 case Builtin::BI__sync_fetch_and_and_1:
3482 case Builtin::BI__sync_fetch_and_and_2:
3483 case Builtin::BI__sync_fetch_and_and_4:
3484 case Builtin::BI__sync_fetch_and_and_8:
3485 case Builtin::BI__sync_fetch_and_and_16:
3486 BuiltinIndex = 3;
3487 break;
Mike Stump11289f42009-09-09 15:08:12 +00003488
Douglas Gregor73722482011-11-28 16:30:08 +00003489 case Builtin::BI__sync_fetch_and_xor:
3490 case Builtin::BI__sync_fetch_and_xor_1:
3491 case Builtin::BI__sync_fetch_and_xor_2:
3492 case Builtin::BI__sync_fetch_and_xor_4:
3493 case Builtin::BI__sync_fetch_and_xor_8:
3494 case Builtin::BI__sync_fetch_and_xor_16:
3495 BuiltinIndex = 4;
3496 break;
3497
Hal Finkeld2208b52014-10-02 20:53:50 +00003498 case Builtin::BI__sync_fetch_and_nand:
3499 case Builtin::BI__sync_fetch_and_nand_1:
3500 case Builtin::BI__sync_fetch_and_nand_2:
3501 case Builtin::BI__sync_fetch_and_nand_4:
3502 case Builtin::BI__sync_fetch_and_nand_8:
3503 case Builtin::BI__sync_fetch_and_nand_16:
3504 BuiltinIndex = 5;
3505 WarnAboutSemanticsChange = true;
3506 break;
3507
Douglas Gregor73722482011-11-28 16:30:08 +00003508 case Builtin::BI__sync_add_and_fetch:
3509 case Builtin::BI__sync_add_and_fetch_1:
3510 case Builtin::BI__sync_add_and_fetch_2:
3511 case Builtin::BI__sync_add_and_fetch_4:
3512 case Builtin::BI__sync_add_and_fetch_8:
3513 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003514 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003515 break;
3516
3517 case Builtin::BI__sync_sub_and_fetch:
3518 case Builtin::BI__sync_sub_and_fetch_1:
3519 case Builtin::BI__sync_sub_and_fetch_2:
3520 case Builtin::BI__sync_sub_and_fetch_4:
3521 case Builtin::BI__sync_sub_and_fetch_8:
3522 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003523 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003524 break;
3525
3526 case Builtin::BI__sync_and_and_fetch:
3527 case Builtin::BI__sync_and_and_fetch_1:
3528 case Builtin::BI__sync_and_and_fetch_2:
3529 case Builtin::BI__sync_and_and_fetch_4:
3530 case Builtin::BI__sync_and_and_fetch_8:
3531 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003532 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003533 break;
3534
3535 case Builtin::BI__sync_or_and_fetch:
3536 case Builtin::BI__sync_or_and_fetch_1:
3537 case Builtin::BI__sync_or_and_fetch_2:
3538 case Builtin::BI__sync_or_and_fetch_4:
3539 case Builtin::BI__sync_or_and_fetch_8:
3540 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003541 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003542 break;
3543
3544 case Builtin::BI__sync_xor_and_fetch:
3545 case Builtin::BI__sync_xor_and_fetch_1:
3546 case Builtin::BI__sync_xor_and_fetch_2:
3547 case Builtin::BI__sync_xor_and_fetch_4:
3548 case Builtin::BI__sync_xor_and_fetch_8:
3549 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003550 BuiltinIndex = 10;
3551 break;
3552
3553 case Builtin::BI__sync_nand_and_fetch:
3554 case Builtin::BI__sync_nand_and_fetch_1:
3555 case Builtin::BI__sync_nand_and_fetch_2:
3556 case Builtin::BI__sync_nand_and_fetch_4:
3557 case Builtin::BI__sync_nand_and_fetch_8:
3558 case Builtin::BI__sync_nand_and_fetch_16:
3559 BuiltinIndex = 11;
3560 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003561 break;
Mike Stump11289f42009-09-09 15:08:12 +00003562
Chris Lattnerdc046542009-05-08 06:58:22 +00003563 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003564 case Builtin::BI__sync_val_compare_and_swap_1:
3565 case Builtin::BI__sync_val_compare_and_swap_2:
3566 case Builtin::BI__sync_val_compare_and_swap_4:
3567 case Builtin::BI__sync_val_compare_and_swap_8:
3568 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003569 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003570 NumFixed = 2;
3571 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003572
Chris Lattnerdc046542009-05-08 06:58:22 +00003573 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003574 case Builtin::BI__sync_bool_compare_and_swap_1:
3575 case Builtin::BI__sync_bool_compare_and_swap_2:
3576 case Builtin::BI__sync_bool_compare_and_swap_4:
3577 case Builtin::BI__sync_bool_compare_and_swap_8:
3578 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003579 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003580 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003581 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003582 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003583
3584 case Builtin::BI__sync_lock_test_and_set:
3585 case Builtin::BI__sync_lock_test_and_set_1:
3586 case Builtin::BI__sync_lock_test_and_set_2:
3587 case Builtin::BI__sync_lock_test_and_set_4:
3588 case Builtin::BI__sync_lock_test_and_set_8:
3589 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003590 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003591 break;
3592
Chris Lattnerdc046542009-05-08 06:58:22 +00003593 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003594 case Builtin::BI__sync_lock_release_1:
3595 case Builtin::BI__sync_lock_release_2:
3596 case Builtin::BI__sync_lock_release_4:
3597 case Builtin::BI__sync_lock_release_8:
3598 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003599 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003600 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003601 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003602 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003603
3604 case Builtin::BI__sync_swap:
3605 case Builtin::BI__sync_swap_1:
3606 case Builtin::BI__sync_swap_2:
3607 case Builtin::BI__sync_swap_4:
3608 case Builtin::BI__sync_swap_8:
3609 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003610 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003611 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003612 }
Mike Stump11289f42009-09-09 15:08:12 +00003613
Chris Lattnerdc046542009-05-08 06:58:22 +00003614 // Now that we know how many fixed arguments we expect, first check that we
3615 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003616 if (TheCall->getNumArgs() < 1+NumFixed) {
3617 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3618 << 0 << 1+NumFixed << TheCall->getNumArgs()
3619 << TheCall->getCallee()->getSourceRange();
3620 return ExprError();
3621 }
Mike Stump11289f42009-09-09 15:08:12 +00003622
Hal Finkeld2208b52014-10-02 20:53:50 +00003623 if (WarnAboutSemanticsChange) {
3624 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3625 << TheCall->getCallee()->getSourceRange();
3626 }
3627
Chris Lattner5b9241b2009-05-08 15:36:58 +00003628 // Get the decl for the concrete builtin from this, we can tell what the
3629 // concrete integer type we should convert to is.
3630 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003631 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003632 FunctionDecl *NewBuiltinDecl;
3633 if (NewBuiltinID == BuiltinID)
3634 NewBuiltinDecl = FDecl;
3635 else {
3636 // Perform builtin lookup to avoid redeclaring it.
3637 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3638 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3639 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3640 assert(Res.getFoundDecl());
3641 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003642 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003643 return ExprError();
3644 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003645
John McCallcf142162010-08-07 06:22:56 +00003646 // The first argument --- the pointer --- has a fixed type; we
3647 // deduce the types of the rest of the arguments accordingly. Walk
3648 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003649 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003650 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003651
Chris Lattnerdc046542009-05-08 06:58:22 +00003652 // GCC does an implicit conversion to the pointer or integer ValType. This
3653 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003654 // Initialize the argument.
3655 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3656 ValType, /*consume*/ false);
3657 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003658 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003659 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003660
Chris Lattnerdc046542009-05-08 06:58:22 +00003661 // Okay, we have something that *can* be converted to the right type. Check
3662 // to see if there is a potentially weird extension going on here. This can
3663 // happen when you do an atomic operation on something like an char* and
3664 // pass in 42. The 42 gets converted to char. This is even more strange
3665 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003666 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003667 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003668 }
Mike Stump11289f42009-09-09 15:08:12 +00003669
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003670 ASTContext& Context = this->getASTContext();
3671
3672 // Create a new DeclRefExpr to refer to the new decl.
3673 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3674 Context,
3675 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003676 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003677 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003678 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003679 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003680 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003681 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003682
Chris Lattnerdc046542009-05-08 06:58:22 +00003683 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003684 // FIXME: This loses syntactic information.
3685 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3686 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3687 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003688 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003689
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003690 // Change the result type of the call to match the original value type. This
3691 // is arbitrary, but the codegen for these builtins ins design to handle it
3692 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003693 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003694
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003695 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003696}
3697
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003698/// SemaBuiltinNontemporalOverloaded - We have a call to
3699/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3700/// overloaded function based on the pointer type of its last argument.
3701///
3702/// This function goes through and does final semantic checking for these
3703/// builtins.
3704ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3705 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3706 DeclRefExpr *DRE =
3707 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3708 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3709 unsigned BuiltinID = FDecl->getBuiltinID();
3710 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3711 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3712 "Unexpected nontemporal load/store builtin!");
3713 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3714 unsigned numArgs = isStore ? 2 : 1;
3715
3716 // Ensure that we have the proper number of arguments.
3717 if (checkArgCount(*this, TheCall, numArgs))
3718 return ExprError();
3719
3720 // Inspect the last argument of the nontemporal builtin. This should always
3721 // be a pointer type, from which we imply the type of the memory access.
3722 // Because it is a pointer type, we don't have to worry about any implicit
3723 // casts here.
3724 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3725 ExprResult PointerArgResult =
3726 DefaultFunctionArrayLvalueConversion(PointerArg);
3727
3728 if (PointerArgResult.isInvalid())
3729 return ExprError();
3730 PointerArg = PointerArgResult.get();
3731 TheCall->setArg(numArgs - 1, PointerArg);
3732
3733 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3734 if (!pointerType) {
3735 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3736 << PointerArg->getType() << PointerArg->getSourceRange();
3737 return ExprError();
3738 }
3739
3740 QualType ValType = pointerType->getPointeeType();
3741
3742 // Strip any qualifiers off ValType.
3743 ValType = ValType.getUnqualifiedType();
3744 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3745 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3746 !ValType->isVectorType()) {
3747 Diag(DRE->getLocStart(),
3748 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3749 << PointerArg->getType() << PointerArg->getSourceRange();
3750 return ExprError();
3751 }
3752
3753 if (!isStore) {
3754 TheCall->setType(ValType);
3755 return TheCallResult;
3756 }
3757
3758 ExprResult ValArg = TheCall->getArg(0);
3759 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3760 Context, ValType, /*consume*/ false);
3761 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3762 if (ValArg.isInvalid())
3763 return ExprError();
3764
3765 TheCall->setArg(0, ValArg.get());
3766 TheCall->setType(Context.VoidTy);
3767 return TheCallResult;
3768}
3769
Chris Lattner6436fb62009-02-18 06:01:06 +00003770/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003771/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003772/// Note: It might also make sense to do the UTF-16 conversion here (would
3773/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003774bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003775 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003776 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3777
Douglas Gregorfb65e592011-07-27 05:40:30 +00003778 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003779 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3780 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003781 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003782 }
Mike Stump11289f42009-09-09 15:08:12 +00003783
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003784 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003785 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003786 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003787 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3788 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3789 llvm::UTF16 *ToPtr = &ToBuf[0];
3790
3791 llvm::ConversionResult Result =
3792 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3793 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003794 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003795 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003796 Diag(Arg->getLocStart(),
3797 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3798 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003799 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003800}
3801
Mehdi Amini06d367c2016-10-24 20:39:34 +00003802/// CheckObjCString - Checks that the format string argument to the os_log()
3803/// and os_trace() functions is correct, and converts it to const char *.
3804ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3805 Arg = Arg->IgnoreParenCasts();
3806 auto *Literal = dyn_cast<StringLiteral>(Arg);
3807 if (!Literal) {
3808 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3809 Literal = ObjcLiteral->getString();
3810 }
3811 }
3812
3813 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3814 return ExprError(
3815 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3816 << Arg->getSourceRange());
3817 }
3818
3819 ExprResult Result(Literal);
3820 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3821 InitializedEntity Entity =
3822 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3823 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3824 return Result;
3825}
3826
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003827/// Check that the user is calling the appropriate va_start builtin for the
3828/// target and calling convention.
3829static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3830 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3831 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003832 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003833 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003834 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3835 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003836 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003837 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3838 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3839 if (IsMSVAStart) {
3840 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003841 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003842 return S.Diag(Fn->getLocStart(),
3843 diag::err_ms_va_start_used_in_sysv_function);
3844 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003845 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003846 // On x64 Windows, don't allow this in System V ABI functions.
3847 // (Yes, that means there's no corresponding way to support variadic
3848 // System V ABI functions on Windows.)
3849 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003850 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003851 return S.Diag(Fn->getLocStart(),
3852 diag::err_va_start_used_in_wrong_abi_function)
3853 << !IsWindows;
3854 }
3855 return false;
3856 }
3857
3858 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003859 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003860 return false;
3861}
3862
3863static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3864 ParmVarDecl **LastParam = nullptr) {
3865 // Determine whether the current function, block, or obj-c method is variadic
3866 // and get its parameter list.
3867 bool IsVariadic = false;
3868 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003869 DeclContext *Caller = S.CurContext;
3870 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3871 IsVariadic = Block->isVariadic();
3872 Params = Block->parameters();
3873 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003874 IsVariadic = FD->isVariadic();
3875 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003876 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003877 IsVariadic = MD->isVariadic();
3878 // FIXME: This isn't correct for methods (results in bogus warning).
3879 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003880 } else if (isa<CapturedDecl>(Caller)) {
3881 // We don't support va_start in a CapturedDecl.
3882 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3883 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003884 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003885 // This must be some other declcontext that parses exprs.
3886 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3887 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003888 }
3889
3890 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003891 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003892 return true;
3893 }
3894
3895 if (LastParam)
3896 *LastParam = Params.empty() ? nullptr : Params.back();
3897
3898 return false;
3899}
3900
Charles Davisc7d5c942015-09-17 20:55:33 +00003901/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3902/// for validity. Emit an error and return true on failure; return false
3903/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003904bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003905 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003906
3907 if (checkVAStartABI(*this, BuiltinID, Fn))
3908 return true;
3909
Chris Lattner08464942007-12-28 05:29:59 +00003910 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003911 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003912 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003913 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3914 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003915 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003916 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003917 return true;
3918 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003919
3920 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003921 return Diag(TheCall->getLocEnd(),
3922 diag::err_typecheck_call_too_few_args_at_least)
3923 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003924 }
3925
John McCall29ad95b2011-08-27 01:09:30 +00003926 // Type-check the first argument normally.
3927 if (checkBuiltinArgument(*this, TheCall, 0))
3928 return true;
3929
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003930 // Check that the current function is variadic, and get its last parameter.
3931 ParmVarDecl *LastParam;
3932 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003933 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003934
Chris Lattner43be2e62007-12-19 23:59:04 +00003935 // Verify that the second argument to the builtin is the last argument of the
3936 // current function or method.
3937 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003938 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003939
Nico Weber9eea7642013-05-24 23:31:57 +00003940 // These are valid if SecondArgIsLastNamedArgument is false after the next
3941 // block.
3942 QualType Type;
3943 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003944 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003945
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003946 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3947 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003948 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003949
3950 Type = PV->getType();
3951 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003952 IsCRegister =
3953 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003954 }
3955 }
Mike Stump11289f42009-09-09 15:08:12 +00003956
Chris Lattner43be2e62007-12-19 23:59:04 +00003957 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003958 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003959 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003960 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003961 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3962 // Promotable integers are UB, but enumerations need a bit of
3963 // extra checking to see what their promotable type actually is.
3964 if (!Type->isPromotableIntegerType())
3965 return false;
3966 if (!Type->isEnumeralType())
3967 return true;
3968 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3969 return !(ED &&
3970 Context.typesAreCompatible(ED->getPromotionType(), Type));
3971 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003972 unsigned Reason = 0;
3973 if (Type->isReferenceType()) Reason = 1;
3974 else if (IsCRegister) Reason = 2;
3975 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003976 Diag(ParamLoc, diag::note_parameter_type) << Type;
3977 }
3978
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003979 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003980 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003981}
Chris Lattner43be2e62007-12-19 23:59:04 +00003982
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00003983bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003984 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3985 // const char *named_addr);
3986
3987 Expr *Func = Call->getCallee();
3988
3989 if (Call->getNumArgs() < 3)
3990 return Diag(Call->getLocEnd(),
3991 diag::err_typecheck_call_too_few_args_at_least)
3992 << 0 /*function call*/ << 3 << Call->getNumArgs();
3993
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003994 // Type-check the first argument normally.
3995 if (checkBuiltinArgument(*this, Call, 0))
3996 return true;
3997
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003998 // Check that the current function is variadic.
3999 if (checkVAStartIsInVariadicFunction(*this, Func))
4000 return true;
4001
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004002 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004003
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004004 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4005 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4006
4007 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4008 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4009
4010 const QualType &ConstCharPtrTy =
4011 Context.getPointerType(Context.CharTy.withConst());
4012 if (!Arg1Ty->isPointerType() ||
4013 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4014 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4015 << Arg1->getType() << ConstCharPtrTy
4016 << 1 /* different class */
4017 << 0 /* qualifier difference */
4018 << 3 /* parameter mismatch */
4019 << 2 << Arg1->getType() << ConstCharPtrTy;
4020
4021 const QualType SizeTy = Context.getSizeType();
4022 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4023 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4024 << Arg2->getType() << SizeTy
4025 << 1 /* different class */
4026 << 0 /* qualifier difference */
4027 << 3 /* parameter mismatch */
4028 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004029
4030 return false;
4031}
4032
Chris Lattner2da14fb2007-12-20 00:26:33 +00004033/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4034/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004035bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4036 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004037 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004038 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004039 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004040 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004041 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004042 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004043 << SourceRange(TheCall->getArg(2)->getLocStart(),
4044 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004045
John Wiegley01296292011-04-08 18:41:53 +00004046 ExprResult OrigArg0 = TheCall->getArg(0);
4047 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004048
Chris Lattner2da14fb2007-12-20 00:26:33 +00004049 // Do standard promotions between the two arguments, returning their common
4050 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004051 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004052 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4053 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004054
4055 // Make sure any conversions are pushed back into the call; this is
4056 // type safe since unordered compare builtins are declared as "_Bool
4057 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004058 TheCall->setArg(0, OrigArg0.get());
4059 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004060
John Wiegley01296292011-04-08 18:41:53 +00004061 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004062 return false;
4063
Chris Lattner2da14fb2007-12-20 00:26:33 +00004064 // If the common type isn't a real floating type, then the arguments were
4065 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004066 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004067 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004068 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004069 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4070 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004071
Chris Lattner2da14fb2007-12-20 00:26:33 +00004072 return false;
4073}
4074
Benjamin Kramer634fc102010-02-15 22:42:31 +00004075/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4076/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004077/// to check everything. We expect the last argument to be a floating point
4078/// value.
4079bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4080 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004081 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004082 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004083 if (TheCall->getNumArgs() > NumArgs)
4084 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004085 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004086 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004087 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004088 (*(TheCall->arg_end()-1))->getLocEnd());
4089
Benjamin Kramer64aae502010-02-16 10:07:31 +00004090 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004091
Eli Friedman7e4faac2009-08-31 20:06:00 +00004092 if (OrigArg->isTypeDependent())
4093 return false;
4094
Chris Lattner68784ef2010-05-06 05:50:07 +00004095 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004096 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004097 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004098 diag::err_typecheck_call_invalid_unary_fp)
4099 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004100
Neil Hickey88c0fac2016-12-13 16:22:50 +00004101 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004102 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004103 // Only remove standard FloatCasts, leaving other casts inplace
4104 if (Cast->getCastKind() == CK_FloatingCast) {
4105 Expr *CastArg = Cast->getSubExpr();
4106 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4107 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4108 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4109 "promotion from float to either float or double is the only expected cast here");
4110 Cast->setSubExpr(nullptr);
4111 TheCall->setArg(NumArgs-1, CastArg);
4112 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004113 }
4114 }
4115
Eli Friedman7e4faac2009-08-31 20:06:00 +00004116 return false;
4117}
4118
Tony Jiangbbc48e92017-05-24 15:13:32 +00004119// Customized Sema Checking for VSX builtins that have the following signature:
4120// vector [...] builtinName(vector [...], vector [...], const int);
4121// Which takes the same type of vectors (any legal vector type) for the first
4122// two arguments and takes compile time constant for the third argument.
4123// Example builtins are :
4124// vector double vec_xxpermdi(vector double, vector double, int);
4125// vector short vec_xxsldwi(vector short, vector short, int);
4126bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4127 unsigned ExpectedNumArgs = 3;
4128 if (TheCall->getNumArgs() < ExpectedNumArgs)
4129 return Diag(TheCall->getLocEnd(),
4130 diag::err_typecheck_call_too_few_args_at_least)
4131 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4132 << TheCall->getSourceRange();
4133
4134 if (TheCall->getNumArgs() > ExpectedNumArgs)
4135 return Diag(TheCall->getLocEnd(),
4136 diag::err_typecheck_call_too_many_args_at_most)
4137 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4138 << TheCall->getSourceRange();
4139
4140 // Check the third argument is a compile time constant
4141 llvm::APSInt Value;
4142 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4143 return Diag(TheCall->getLocStart(),
4144 diag::err_vsx_builtin_nonconstant_argument)
4145 << 3 /* argument index */ << TheCall->getDirectCallee()
4146 << SourceRange(TheCall->getArg(2)->getLocStart(),
4147 TheCall->getArg(2)->getLocEnd());
4148
4149 QualType Arg1Ty = TheCall->getArg(0)->getType();
4150 QualType Arg2Ty = TheCall->getArg(1)->getType();
4151
4152 // Check the type of argument 1 and argument 2 are vectors.
4153 SourceLocation BuiltinLoc = TheCall->getLocStart();
4154 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4155 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4156 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4157 << TheCall->getDirectCallee()
4158 << SourceRange(TheCall->getArg(0)->getLocStart(),
4159 TheCall->getArg(1)->getLocEnd());
4160 }
4161
4162 // Check the first two arguments are the same type.
4163 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4164 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4165 << TheCall->getDirectCallee()
4166 << SourceRange(TheCall->getArg(0)->getLocStart(),
4167 TheCall->getArg(1)->getLocEnd());
4168 }
4169
4170 // When default clang type checking is turned off and the customized type
4171 // checking is used, the returning type of the function must be explicitly
4172 // set. Otherwise it is _Bool by default.
4173 TheCall->setType(Arg1Ty);
4174
4175 return false;
4176}
4177
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004178/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4179// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004180ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004181 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004182 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004183 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004184 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4185 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004186
Nate Begemana0110022010-06-08 00:16:34 +00004187 // Determine which of the following types of shufflevector we're checking:
4188 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004189 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004190 QualType resType = TheCall->getArg(0)->getType();
4191 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004192
Douglas Gregorc25f7662009-05-19 22:10:17 +00004193 if (!TheCall->getArg(0)->isTypeDependent() &&
4194 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004195 QualType LHSType = TheCall->getArg(0)->getType();
4196 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004197
Craig Topperbaca3892013-07-29 06:47:04 +00004198 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4199 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004200 diag::err_vec_builtin_non_vector)
4201 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004202 << SourceRange(TheCall->getArg(0)->getLocStart(),
4203 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004204
Nate Begemana0110022010-06-08 00:16:34 +00004205 numElements = LHSType->getAs<VectorType>()->getNumElements();
4206 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004207
Nate Begemana0110022010-06-08 00:16:34 +00004208 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4209 // with mask. If so, verify that RHS is an integer vector type with the
4210 // same number of elts as lhs.
4211 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004212 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004213 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004214 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004215 diag::err_vec_builtin_incompatible_vector)
4216 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004217 << SourceRange(TheCall->getArg(1)->getLocStart(),
4218 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004219 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004220 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004221 diag::err_vec_builtin_incompatible_vector)
4222 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004223 << SourceRange(TheCall->getArg(0)->getLocStart(),
4224 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004225 } else if (numElements != numResElements) {
4226 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004227 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004228 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004229 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004230 }
4231
4232 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004233 if (TheCall->getArg(i)->isTypeDependent() ||
4234 TheCall->getArg(i)->isValueDependent())
4235 continue;
4236
Nate Begemana0110022010-06-08 00:16:34 +00004237 llvm::APSInt Result(32);
4238 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4239 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004240 diag::err_shufflevector_nonconstant_argument)
4241 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004242
Craig Topper50ad5b72013-08-03 17:40:38 +00004243 // Allow -1 which will be translated to undef in the IR.
4244 if (Result.isSigned() && Result.isAllOnesValue())
4245 continue;
4246
Chris Lattner7ab824e2008-08-10 02:05:13 +00004247 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004248 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004249 diag::err_shufflevector_argument_too_large)
4250 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004251 }
4252
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004253 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004254
Chris Lattner7ab824e2008-08-10 02:05:13 +00004255 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004256 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004257 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004258 }
4259
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004260 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4261 TheCall->getCallee()->getLocStart(),
4262 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004263}
Chris Lattner43be2e62007-12-19 23:59:04 +00004264
Hal Finkelc4d7c822013-09-18 03:29:45 +00004265/// SemaConvertVectorExpr - Handle __builtin_convertvector
4266ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4267 SourceLocation BuiltinLoc,
4268 SourceLocation RParenLoc) {
4269 ExprValueKind VK = VK_RValue;
4270 ExprObjectKind OK = OK_Ordinary;
4271 QualType DstTy = TInfo->getType();
4272 QualType SrcTy = E->getType();
4273
4274 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4275 return ExprError(Diag(BuiltinLoc,
4276 diag::err_convertvector_non_vector)
4277 << E->getSourceRange());
4278 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4279 return ExprError(Diag(BuiltinLoc,
4280 diag::err_convertvector_non_vector_type));
4281
4282 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4283 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4284 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4285 if (SrcElts != DstElts)
4286 return ExprError(Diag(BuiltinLoc,
4287 diag::err_convertvector_incompatible_vector)
4288 << E->getSourceRange());
4289 }
4290
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004291 return new (Context)
4292 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004293}
4294
Daniel Dunbarb7257262008-07-21 22:59:13 +00004295/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4296// This is declared to take (const void*, ...) and can take two
4297// optional constant int args.
4298bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004299 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004300
Chris Lattner3b054132008-11-19 05:08:23 +00004301 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004302 return Diag(TheCall->getLocEnd(),
4303 diag::err_typecheck_call_too_many_args_at_most)
4304 << 0 /*function call*/ << 3 << NumArgs
4305 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004306
4307 // Argument 0 is checked for us and the remaining arguments must be
4308 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004309 for (unsigned i = 1; i != NumArgs; ++i)
4310 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004311 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004312
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004313 return false;
4314}
4315
Hal Finkelf0417332014-07-17 14:25:55 +00004316/// SemaBuiltinAssume - Handle __assume (MS Extension).
4317// __assume does not evaluate its arguments, and should warn if its argument
4318// has side effects.
4319bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4320 Expr *Arg = TheCall->getArg(0);
4321 if (Arg->isInstantiationDependent()) return false;
4322
4323 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004324 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004325 << Arg->getSourceRange()
4326 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4327
4328 return false;
4329}
4330
David Majnemer86b1bfa2016-10-31 18:07:57 +00004331/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004332/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4333/// than 8.
4334bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4335 // The alignment must be a constant integer.
4336 Expr *Arg = TheCall->getArg(1);
4337
4338 // We can't check the value of a dependent argument.
4339 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004340 if (const auto *UE =
4341 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4342 if (UE->getKind() == UETT_AlignOf)
4343 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4344 << Arg->getSourceRange();
4345
David Majnemer51169932016-10-31 05:37:48 +00004346 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4347
4348 if (!Result.isPowerOf2())
4349 return Diag(TheCall->getLocStart(),
4350 diag::err_alignment_not_power_of_two)
4351 << Arg->getSourceRange();
4352
4353 if (Result < Context.getCharWidth())
4354 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4355 << (unsigned)Context.getCharWidth()
4356 << Arg->getSourceRange();
4357
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004358 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004359 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004360 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004361 << Arg->getSourceRange();
4362 }
4363
4364 return false;
4365}
4366
4367/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004368/// as (const void*, size_t, ...) and can take one optional constant int arg.
4369bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4370 unsigned NumArgs = TheCall->getNumArgs();
4371
4372 if (NumArgs > 3)
4373 return Diag(TheCall->getLocEnd(),
4374 diag::err_typecheck_call_too_many_args_at_most)
4375 << 0 /*function call*/ << 3 << NumArgs
4376 << TheCall->getSourceRange();
4377
4378 // The alignment must be a constant integer.
4379 Expr *Arg = TheCall->getArg(1);
4380
4381 // We can't check the value of a dependent argument.
4382 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4383 llvm::APSInt Result;
4384 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4385 return true;
4386
4387 if (!Result.isPowerOf2())
4388 return Diag(TheCall->getLocStart(),
4389 diag::err_alignment_not_power_of_two)
4390 << Arg->getSourceRange();
4391 }
4392
4393 if (NumArgs > 2) {
4394 ExprResult Arg(TheCall->getArg(2));
4395 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4396 Context.getSizeType(), false);
4397 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4398 if (Arg.isInvalid()) return true;
4399 TheCall->setArg(2, Arg.get());
4400 }
Hal Finkelf0417332014-07-17 14:25:55 +00004401
4402 return false;
4403}
4404
Mehdi Amini06d367c2016-10-24 20:39:34 +00004405bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4406 unsigned BuiltinID =
4407 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4408 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4409
4410 unsigned NumArgs = TheCall->getNumArgs();
4411 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4412 if (NumArgs < NumRequiredArgs) {
4413 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4414 << 0 /* function call */ << NumRequiredArgs << NumArgs
4415 << TheCall->getSourceRange();
4416 }
4417 if (NumArgs >= NumRequiredArgs + 0x100) {
4418 return Diag(TheCall->getLocEnd(),
4419 diag::err_typecheck_call_too_many_args_at_most)
4420 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4421 << TheCall->getSourceRange();
4422 }
4423 unsigned i = 0;
4424
4425 // For formatting call, check buffer arg.
4426 if (!IsSizeCall) {
4427 ExprResult Arg(TheCall->getArg(i));
4428 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4429 Context, Context.VoidPtrTy, false);
4430 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4431 if (Arg.isInvalid())
4432 return true;
4433 TheCall->setArg(i, Arg.get());
4434 i++;
4435 }
4436
4437 // Check string literal arg.
4438 unsigned FormatIdx = i;
4439 {
4440 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4441 if (Arg.isInvalid())
4442 return true;
4443 TheCall->setArg(i, Arg.get());
4444 i++;
4445 }
4446
4447 // Make sure variadic args are scalar.
4448 unsigned FirstDataArg = i;
4449 while (i < NumArgs) {
4450 ExprResult Arg = DefaultVariadicArgumentPromotion(
4451 TheCall->getArg(i), VariadicFunction, nullptr);
4452 if (Arg.isInvalid())
4453 return true;
4454 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4455 if (ArgSize.getQuantity() >= 0x100) {
4456 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4457 << i << (int)ArgSize.getQuantity() << 0xff
4458 << TheCall->getSourceRange();
4459 }
4460 TheCall->setArg(i, Arg.get());
4461 i++;
4462 }
4463
4464 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4465 // call to avoid duplicate diagnostics.
4466 if (!IsSizeCall) {
4467 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4468 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4469 bool Success = CheckFormatArguments(
4470 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4471 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4472 CheckedVarArgs);
4473 if (!Success)
4474 return true;
4475 }
4476
4477 if (IsSizeCall) {
4478 TheCall->setType(Context.getSizeType());
4479 } else {
4480 TheCall->setType(Context.VoidPtrTy);
4481 }
4482 return false;
4483}
4484
Eric Christopher8d0c6212010-04-17 02:26:23 +00004485/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4486/// TheCall is a constant expression.
4487bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4488 llvm::APSInt &Result) {
4489 Expr *Arg = TheCall->getArg(ArgNum);
4490 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4491 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4492
4493 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4494
4495 if (!Arg->isIntegerConstantExpr(Result, Context))
4496 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004497 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004498
Chris Lattnerd545ad12009-09-23 06:06:36 +00004499 return false;
4500}
4501
Richard Sandiford28940af2014-04-16 08:47:51 +00004502/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4503/// TheCall is a constant expression in the range [Low, High].
4504bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4505 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004506 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004507
4508 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004509 Expr *Arg = TheCall->getArg(ArgNum);
4510 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004511 return false;
4512
Eric Christopher8d0c6212010-04-17 02:26:23 +00004513 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004514 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004515 return true;
4516
Richard Sandiford28940af2014-04-16 08:47:51 +00004517 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004518 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004519 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004520
4521 return false;
4522}
4523
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004524/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4525/// TheCall is a constant expression is a multiple of Num..
4526bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4527 unsigned Num) {
4528 llvm::APSInt Result;
4529
4530 // We can't check the value of a dependent argument.
4531 Expr *Arg = TheCall->getArg(ArgNum);
4532 if (Arg->isTypeDependent() || Arg->isValueDependent())
4533 return false;
4534
4535 // Check constant-ness first.
4536 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4537 return true;
4538
4539 if (Result.getSExtValue() % Num != 0)
4540 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4541 << Num << Arg->getSourceRange();
4542
4543 return false;
4544}
4545
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004546/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4547/// TheCall is an ARM/AArch64 special register string literal.
4548bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4549 int ArgNum, unsigned ExpectedFieldNum,
4550 bool AllowName) {
4551 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4552 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4553 BuiltinID == ARM::BI__builtin_arm_rsr ||
4554 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4555 BuiltinID == ARM::BI__builtin_arm_wsr ||
4556 BuiltinID == ARM::BI__builtin_arm_wsrp;
4557 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4558 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4559 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4560 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4561 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4562 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4563 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4564
4565 // We can't check the value of a dependent argument.
4566 Expr *Arg = TheCall->getArg(ArgNum);
4567 if (Arg->isTypeDependent() || Arg->isValueDependent())
4568 return false;
4569
4570 // Check if the argument is a string literal.
4571 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4572 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4573 << Arg->getSourceRange();
4574
4575 // Check the type of special register given.
4576 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4577 SmallVector<StringRef, 6> Fields;
4578 Reg.split(Fields, ":");
4579
4580 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4581 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4582 << Arg->getSourceRange();
4583
4584 // If the string is the name of a register then we cannot check that it is
4585 // valid here but if the string is of one the forms described in ACLE then we
4586 // can check that the supplied fields are integers and within the valid
4587 // ranges.
4588 if (Fields.size() > 1) {
4589 bool FiveFields = Fields.size() == 5;
4590
4591 bool ValidString = true;
4592 if (IsARMBuiltin) {
4593 ValidString &= Fields[0].startswith_lower("cp") ||
4594 Fields[0].startswith_lower("p");
4595 if (ValidString)
4596 Fields[0] =
4597 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4598
4599 ValidString &= Fields[2].startswith_lower("c");
4600 if (ValidString)
4601 Fields[2] = Fields[2].drop_front(1);
4602
4603 if (FiveFields) {
4604 ValidString &= Fields[3].startswith_lower("c");
4605 if (ValidString)
4606 Fields[3] = Fields[3].drop_front(1);
4607 }
4608 }
4609
4610 SmallVector<int, 5> Ranges;
4611 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004612 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004613 else
4614 Ranges.append({15, 7, 15});
4615
4616 for (unsigned i=0; i<Fields.size(); ++i) {
4617 int IntField;
4618 ValidString &= !Fields[i].getAsInteger(10, IntField);
4619 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4620 }
4621
4622 if (!ValidString)
4623 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4624 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004625 } else if (IsAArch64Builtin && Fields.size() == 1) {
4626 // If the register name is one of those that appear in the condition below
4627 // and the special register builtin being used is one of the write builtins,
4628 // then we require that the argument provided for writing to the register
4629 // is an integer constant expression. This is because it will be lowered to
4630 // an MSR (immediate) instruction, so we need to know the immediate at
4631 // compile time.
4632 if (TheCall->getNumArgs() != 2)
4633 return false;
4634
4635 std::string RegLower = Reg.lower();
4636 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4637 RegLower != "pan" && RegLower != "uao")
4638 return false;
4639
4640 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4641 }
4642
4643 return false;
4644}
4645
Eli Friedmanc97d0142009-05-03 06:04:26 +00004646/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004647/// This checks that the target supports __builtin_longjmp and
4648/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004649bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004650 if (!Context.getTargetInfo().hasSjLjLowering())
4651 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4652 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4653
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004654 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004655 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004656
Eric Christopher8d0c6212010-04-17 02:26:23 +00004657 // TODO: This is less than ideal. Overload this to take a value.
4658 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4659 return true;
4660
4661 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004662 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4663 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4664
4665 return false;
4666}
4667
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004668/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4669/// This checks that the target supports __builtin_setjmp.
4670bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4671 if (!Context.getTargetInfo().hasSjLjLowering())
4672 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4673 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4674 return false;
4675}
4676
Richard Smithd7293d72013-08-05 18:49:43 +00004677namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004678
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004679class UncoveredArgHandler {
4680 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004681
4682 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004683 SmallVector<const Expr *, 4> DiagnosticExprs;
4684
4685public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004686 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004687
4688 bool hasUncoveredArg() const {
4689 return (FirstUncoveredArg >= 0);
4690 }
4691
4692 unsigned getUncoveredArg() const {
4693 assert(hasUncoveredArg() && "no uncovered argument");
4694 return FirstUncoveredArg;
4695 }
4696
4697 void setAllCovered() {
4698 // A string has been found with all arguments covered, so clear out
4699 // the diagnostics.
4700 DiagnosticExprs.clear();
4701 FirstUncoveredArg = AllCovered;
4702 }
4703
4704 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4705 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4706
4707 // Don't update if a previous string covers all arguments.
4708 if (FirstUncoveredArg == AllCovered)
4709 return;
4710
4711 // UncoveredArgHandler tracks the highest uncovered argument index
4712 // and with it all the strings that match this index.
4713 if (NewFirstUncoveredArg == FirstUncoveredArg)
4714 DiagnosticExprs.push_back(StrExpr);
4715 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4716 DiagnosticExprs.clear();
4717 DiagnosticExprs.push_back(StrExpr);
4718 FirstUncoveredArg = NewFirstUncoveredArg;
4719 }
4720 }
4721
4722 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4723};
4724
Richard Smithd7293d72013-08-05 18:49:43 +00004725enum StringLiteralCheckType {
4726 SLCT_NotALiteral,
4727 SLCT_UncheckedLiteral,
4728 SLCT_CheckedLiteral
4729};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004730
4731} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004732
Stephen Hines648c3692016-09-16 01:07:04 +00004733static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4734 BinaryOperatorKind BinOpKind,
4735 bool AddendIsRight) {
4736 unsigned BitWidth = Offset.getBitWidth();
4737 unsigned AddendBitWidth = Addend.getBitWidth();
4738 // There might be negative interim results.
4739 if (Addend.isUnsigned()) {
4740 Addend = Addend.zext(++AddendBitWidth);
4741 Addend.setIsSigned(true);
4742 }
4743 // Adjust the bit width of the APSInts.
4744 if (AddendBitWidth > BitWidth) {
4745 Offset = Offset.sext(AddendBitWidth);
4746 BitWidth = AddendBitWidth;
4747 } else if (BitWidth > AddendBitWidth) {
4748 Addend = Addend.sext(BitWidth);
4749 }
4750
4751 bool Ov = false;
4752 llvm::APSInt ResOffset = Offset;
4753 if (BinOpKind == BO_Add)
4754 ResOffset = Offset.sadd_ov(Addend, Ov);
4755 else {
4756 assert(AddendIsRight && BinOpKind == BO_Sub &&
4757 "operator must be add or sub with addend on the right");
4758 ResOffset = Offset.ssub_ov(Addend, Ov);
4759 }
4760
4761 // We add an offset to a pointer here so we should support an offset as big as
4762 // possible.
4763 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004764 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4765 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004766 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004767 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4768 return;
4769 }
4770
4771 Offset = ResOffset;
4772}
4773
4774namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004775
Stephen Hines648c3692016-09-16 01:07:04 +00004776// This is a wrapper class around StringLiteral to support offsetted string
4777// literals as format strings. It takes the offset into account when returning
4778// the string and its length or the source locations to display notes correctly.
4779class FormatStringLiteral {
4780 const StringLiteral *FExpr;
4781 int64_t Offset;
4782
4783 public:
4784 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4785 : FExpr(fexpr), Offset(Offset) {}
4786
4787 StringRef getString() const {
4788 return FExpr->getString().drop_front(Offset);
4789 }
4790
4791 unsigned getByteLength() const {
4792 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4793 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004794
Stephen Hines648c3692016-09-16 01:07:04 +00004795 unsigned getLength() const { return FExpr->getLength() - Offset; }
4796 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4797
4798 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4799
4800 QualType getType() const { return FExpr->getType(); }
4801
4802 bool isAscii() const { return FExpr->isAscii(); }
4803 bool isWide() const { return FExpr->isWide(); }
4804 bool isUTF8() const { return FExpr->isUTF8(); }
4805 bool isUTF16() const { return FExpr->isUTF16(); }
4806 bool isUTF32() const { return FExpr->isUTF32(); }
4807 bool isPascal() const { return FExpr->isPascal(); }
4808
4809 SourceLocation getLocationOfByte(
4810 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4811 const TargetInfo &Target, unsigned *StartToken = nullptr,
4812 unsigned *StartTokenByteOffset = nullptr) const {
4813 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4814 StartToken, StartTokenByteOffset);
4815 }
4816
4817 SourceLocation getLocStart() const LLVM_READONLY {
4818 return FExpr->getLocStart().getLocWithOffset(Offset);
4819 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004820
Stephen Hines648c3692016-09-16 01:07:04 +00004821 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4822};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004823
4824} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00004825
4826static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004827 const Expr *OrigFormatExpr,
4828 ArrayRef<const Expr *> Args,
4829 bool HasVAListArg, unsigned format_idx,
4830 unsigned firstDataArg,
4831 Sema::FormatStringType Type,
4832 bool inFunctionCall,
4833 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004834 llvm::SmallBitVector &CheckedVarArgs,
4835 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004836
Richard Smith55ce3522012-06-25 20:30:08 +00004837// Determine if an expression is a string literal or constant string.
4838// If this function returns false on the arguments to a function expecting a
4839// format string, we will usually need to emit a warning.
4840// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004841static StringLiteralCheckType
4842checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4843 bool HasVAListArg, unsigned format_idx,
4844 unsigned firstDataArg, Sema::FormatStringType Type,
4845 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004846 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004847 UncoveredArgHandler &UncoveredArg,
4848 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004849 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004850 assert(Offset.isSigned() && "invalid offset");
4851
Douglas Gregorc25f7662009-05-19 22:10:17 +00004852 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004853 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004854
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004855 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004856
Richard Smithd7293d72013-08-05 18:49:43 +00004857 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004858 // Technically -Wformat-nonliteral does not warn about this case.
4859 // The behavior of printf and friends in this case is implementation
4860 // dependent. Ideally if the format string cannot be null then
4861 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004862 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004863
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004864 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004865 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004866 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004867 // The expression is a literal if both sub-expressions were, and it was
4868 // completely checked only if both sub-expressions were checked.
4869 const AbstractConditionalOperator *C =
4870 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004871
4872 // Determine whether it is necessary to check both sub-expressions, for
4873 // example, because the condition expression is a constant that can be
4874 // evaluated at compile time.
4875 bool CheckLeft = true, CheckRight = true;
4876
4877 bool Cond;
4878 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4879 if (Cond)
4880 CheckRight = false;
4881 else
4882 CheckLeft = false;
4883 }
4884
Stephen Hines648c3692016-09-16 01:07:04 +00004885 // We need to maintain the offsets for the right and the left hand side
4886 // separately to check if every possible indexed expression is a valid
4887 // string literal. They might have different offsets for different string
4888 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004889 StringLiteralCheckType Left;
4890 if (!CheckLeft)
4891 Left = SLCT_UncheckedLiteral;
4892 else {
4893 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4894 HasVAListArg, format_idx, firstDataArg,
4895 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004896 CheckedVarArgs, UncoveredArg, Offset);
4897 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004898 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004899 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004900 }
4901
Richard Smith55ce3522012-06-25 20:30:08 +00004902 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004903 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004904 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004905 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004906 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004907
4908 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004909 }
4910
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004911 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00004912 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4913 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004914
John McCallc07a0c72011-02-17 10:25:35 +00004915 case Stmt::OpaqueValueExprClass:
4916 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4917 E = src;
4918 goto tryAgain;
4919 }
Richard Smith55ce3522012-06-25 20:30:08 +00004920 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004921
Ted Kremeneka8890832011-02-24 23:03:04 +00004922 case Stmt::PredefinedExprClass:
4923 // While __func__, etc., are technically not string literals, they
4924 // cannot contain format specifiers and thus are not a security
4925 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004926 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004927
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004928 case Stmt::DeclRefExprClass: {
4929 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004930
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004931 // As an exception, do not flag errors for variables binding to
4932 // const string literals.
4933 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4934 bool isConstant = false;
4935 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004936
Richard Smithd7293d72013-08-05 18:49:43 +00004937 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4938 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004939 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004940 isConstant = T.isConstant(S.Context) &&
4941 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004942 } else if (T->isObjCObjectPointerType()) {
4943 // In ObjC, there is usually no "const ObjectPointer" type,
4944 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004945 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004946 }
Mike Stump11289f42009-09-09 15:08:12 +00004947
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004948 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004949 if (const Expr *Init = VD->getAnyInitializer()) {
4950 // Look through initializers like const char c[] = { "foo" }
4951 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4952 if (InitList->isStringLiteralInit())
4953 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4954 }
Richard Smithd7293d72013-08-05 18:49:43 +00004955 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004956 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004957 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004958 /*InFunctionCall*/ false, CheckedVarArgs,
4959 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004960 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004961 }
Mike Stump11289f42009-09-09 15:08:12 +00004962
Anders Carlssonb012ca92009-06-28 19:55:58 +00004963 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4964 // special check to see if the format string is a function parameter
4965 // of the function calling the printf function. If the function
4966 // has an attribute indicating it is a printf-like function, then we
4967 // should suppress warnings concerning non-literals being used in a call
4968 // to a vprintf function. For example:
4969 //
4970 // void
4971 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4972 // va_list ap;
4973 // va_start(ap, fmt);
4974 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4975 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004976 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004977 if (HasVAListArg) {
4978 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4979 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4980 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004981 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004982 // adjust for implicit parameter
4983 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4984 if (MD->isInstance())
4985 ++PVIndex;
4986 // We also check if the formats are compatible.
4987 // We can't pass a 'scanf' string to a 'printf' function.
4988 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004989 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004990 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004991 }
4992 }
4993 }
4994 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004995 }
Mike Stump11289f42009-09-09 15:08:12 +00004996
Richard Smith55ce3522012-06-25 20:30:08 +00004997 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004998 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004999
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005000 case Stmt::CallExprClass:
5001 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005002 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005003 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5004 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5005 unsigned ArgIndex = FA->getFormatIdx();
5006 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5007 if (MD->isInstance())
5008 --ArgIndex;
5009 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00005010
Richard Smithd7293d72013-08-05 18:49:43 +00005011 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005012 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005013 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005014 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005015 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5016 unsigned BuiltinID = FD->getBuiltinID();
5017 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5018 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5019 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005020 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005021 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005022 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005023 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005024 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005025 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005026 }
5027 }
Mike Stump11289f42009-09-09 15:08:12 +00005028
Richard Smith55ce3522012-06-25 20:30:08 +00005029 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005030 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005031 case Stmt::ObjCMessageExprClass: {
5032 const auto *ME = cast<ObjCMessageExpr>(E);
5033 if (const auto *ND = ME->getMethodDecl()) {
5034 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5035 unsigned ArgIndex = FA->getFormatIdx();
5036 const Expr *Arg = ME->getArg(ArgIndex - 1);
5037 return checkFormatStringExpr(
5038 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5039 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5040 }
5041 }
5042
5043 return SLCT_NotALiteral;
5044 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005045 case Stmt::ObjCStringLiteralClass:
5046 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005047 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005048
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005049 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005050 StrE = ObjCFExpr->getString();
5051 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005052 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005053
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005054 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005055 if (Offset.isNegative() || Offset > StrE->getLength()) {
5056 // TODO: It would be better to have an explicit warning for out of
5057 // bounds literals.
5058 return SLCT_NotALiteral;
5059 }
5060 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5061 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005062 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005063 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005064 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005065 }
Mike Stump11289f42009-09-09 15:08:12 +00005066
Richard Smith55ce3522012-06-25 20:30:08 +00005067 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005068 }
Stephen Hines648c3692016-09-16 01:07:04 +00005069 case Stmt::BinaryOperatorClass: {
5070 llvm::APSInt LResult;
5071 llvm::APSInt RResult;
5072
5073 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5074
5075 // A string literal + an int offset is still a string literal.
5076 if (BinOp->isAdditiveOp()) {
5077 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5078 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5079
5080 if (LIsInt != RIsInt) {
5081 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5082
5083 if (LIsInt) {
5084 if (BinOpKind == BO_Add) {
5085 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5086 E = BinOp->getRHS();
5087 goto tryAgain;
5088 }
5089 } else {
5090 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5091 E = BinOp->getLHS();
5092 goto tryAgain;
5093 }
5094 }
Stephen Hines648c3692016-09-16 01:07:04 +00005095 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005096
5097 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005098 }
5099 case Stmt::UnaryOperatorClass: {
5100 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5101 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005102 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005103 llvm::APSInt IndexResult;
5104 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5105 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5106 E = ASE->getBase();
5107 goto tryAgain;
5108 }
5109 }
5110
5111 return SLCT_NotALiteral;
5112 }
Mike Stump11289f42009-09-09 15:08:12 +00005113
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005114 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005115 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005116 }
5117}
5118
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005119Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005120 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005121 .Case("scanf", FST_Scanf)
5122 .Cases("printf", "printf0", FST_Printf)
5123 .Cases("NSString", "CFString", FST_NSString)
5124 .Case("strftime", FST_Strftime)
5125 .Case("strfmon", FST_Strfmon)
5126 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5127 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5128 .Case("os_trace", FST_OSLog)
5129 .Case("os_log", FST_OSLog)
5130 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005131}
5132
Jordan Rose3e0ec582012-07-19 18:10:23 +00005133/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005134/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005135/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005136bool Sema::CheckFormatArguments(const FormatAttr *Format,
5137 ArrayRef<const Expr *> Args,
5138 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005139 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005140 SourceLocation Loc, SourceRange Range,
5141 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005142 FormatStringInfo FSI;
5143 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005144 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005145 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005146 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005147 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005148}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005149
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005150bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005151 bool HasVAListArg, unsigned format_idx,
5152 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005153 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005154 SourceLocation Loc, SourceRange Range,
5155 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005156 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005157 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005158 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005159 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005160 }
Mike Stump11289f42009-09-09 15:08:12 +00005161
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005162 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005163
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005164 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005165 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005166 // Dynamically generated format strings are difficult to
5167 // automatically vet at compile time. Requiring that format strings
5168 // are string literals: (1) permits the checking of format strings by
5169 // the compiler and thereby (2) can practically remove the source of
5170 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005171
Mike Stump11289f42009-09-09 15:08:12 +00005172 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005173 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005174 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005175 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005176 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005177 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005178 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5179 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005180 /*IsFunctionCall*/ true, CheckedVarArgs,
5181 UncoveredArg,
5182 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005183
5184 // Generate a diagnostic where an uncovered argument is detected.
5185 if (UncoveredArg.hasUncoveredArg()) {
5186 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5187 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5188 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5189 }
5190
Richard Smith55ce3522012-06-25 20:30:08 +00005191 if (CT != SLCT_NotALiteral)
5192 // Literal format string found, check done!
5193 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005194
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005195 // Strftime is particular as it always uses a single 'time' argument,
5196 // so it is safe to pass a non-literal string.
5197 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005198 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005199
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005200 // Do not emit diag when the string param is a macro expansion and the
5201 // format is either NSString or CFString. This is a hack to prevent
5202 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5203 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005204 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5205 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005206 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005207
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005208 // If there are no arguments specified, warn with -Wformat-security, otherwise
5209 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005210 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005211 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5212 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005213 switch (Type) {
5214 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005215 break;
5216 case FST_Kprintf:
5217 case FST_FreeBSDKPrintf:
5218 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005219 Diag(FormatLoc, diag::note_format_security_fixit)
5220 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005221 break;
5222 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005223 Diag(FormatLoc, diag::note_format_security_fixit)
5224 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005225 break;
5226 }
5227 } else {
5228 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005229 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005230 }
Richard Smith55ce3522012-06-25 20:30:08 +00005231 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005232}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005233
Ted Kremenekab278de2010-01-28 23:39:18 +00005234namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005235
Ted Kremenek02087932010-07-16 02:11:22 +00005236class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5237protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005238 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005239 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005240 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005241 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005242 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005243 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005244 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005245 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005246 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005247 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005248 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005249 bool usesPositionalArgs = false;
5250 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005251 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005252 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005253 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005254 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005255
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005256public:
Stephen Hines648c3692016-09-16 01:07:04 +00005257 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005258 const Expr *origFormatExpr,
5259 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005260 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005261 ArrayRef<const Expr *> Args, unsigned formatIdx,
5262 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005263 llvm::SmallBitVector &CheckedVarArgs,
5264 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005265 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5266 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5267 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005268 inFunctionCall(inFunctionCall), CallType(callType),
5269 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005270 CoveredArgs.resize(numDataArgs);
5271 CoveredArgs.reset();
5272 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005273
Ted Kremenek019d2242010-01-29 01:50:07 +00005274 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005275
Ted Kremenek02087932010-07-16 02:11:22 +00005276 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005277 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005278
Jordan Rose92303592012-09-08 04:00:03 +00005279 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005280 const analyze_format_string::FormatSpecifier &FS,
5281 const analyze_format_string::ConversionSpecifier &CS,
5282 const char *startSpecifier, unsigned specifierLen,
5283 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005284
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005285 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005286 const analyze_format_string::FormatSpecifier &FS,
5287 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005288
5289 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005290 const analyze_format_string::ConversionSpecifier &CS,
5291 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005292
Craig Toppere14c0f82014-03-12 04:55:44 +00005293 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005294
Craig Toppere14c0f82014-03-12 04:55:44 +00005295 void HandleInvalidPosition(const char *startSpecifier,
5296 unsigned specifierLen,
5297 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005298
Craig Toppere14c0f82014-03-12 04:55:44 +00005299 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005300
Craig Toppere14c0f82014-03-12 04:55:44 +00005301 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005302
Richard Trieu03cf7b72011-10-28 00:41:25 +00005303 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005304 static void
5305 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5306 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5307 bool IsStringLocation, Range StringRange,
5308 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005309
Ted Kremenek02087932010-07-16 02:11:22 +00005310protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005311 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5312 const char *startSpec,
5313 unsigned specifierLen,
5314 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005315
5316 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5317 const char *startSpec,
5318 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005319
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005320 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005321 CharSourceRange getSpecifierRange(const char *startSpecifier,
5322 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005323 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005324
Ted Kremenek5739de72010-01-29 01:06:55 +00005325 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005326
5327 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5328 const analyze_format_string::ConversionSpecifier &CS,
5329 const char *startSpecifier, unsigned specifierLen,
5330 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005331
5332 template <typename Range>
5333 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5334 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005335 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005336};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005337
5338} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005339
Ted Kremenek02087932010-07-16 02:11:22 +00005340SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005341 return OrigFormatExpr->getSourceRange();
5342}
5343
Ted Kremenek02087932010-07-16 02:11:22 +00005344CharSourceRange CheckFormatHandler::
5345getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005346 SourceLocation Start = getLocationOfByte(startSpecifier);
5347 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5348
5349 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005350 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005351
5352 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005353}
5354
Ted Kremenek02087932010-07-16 02:11:22 +00005355SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005356 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5357 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005358}
5359
Ted Kremenek02087932010-07-16 02:11:22 +00005360void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5361 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005362 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5363 getLocationOfByte(startSpecifier),
5364 /*IsStringLocation*/true,
5365 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005366}
5367
Jordan Rose92303592012-09-08 04:00:03 +00005368void CheckFormatHandler::HandleInvalidLengthModifier(
5369 const analyze_format_string::FormatSpecifier &FS,
5370 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005371 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005372 using namespace analyze_format_string;
5373
5374 const LengthModifier &LM = FS.getLengthModifier();
5375 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5376
5377 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005378 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005379 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005380 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005381 getLocationOfByte(LM.getStart()),
5382 /*IsStringLocation*/true,
5383 getSpecifierRange(startSpecifier, specifierLen));
5384
5385 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5386 << FixedLM->toString()
5387 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5388
5389 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005390 FixItHint Hint;
5391 if (DiagID == diag::warn_format_nonsensical_length)
5392 Hint = FixItHint::CreateRemoval(LMRange);
5393
5394 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005395 getLocationOfByte(LM.getStart()),
5396 /*IsStringLocation*/true,
5397 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005398 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005399 }
5400}
5401
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005402void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005403 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005404 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005405 using namespace analyze_format_string;
5406
5407 const LengthModifier &LM = FS.getLengthModifier();
5408 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5409
5410 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005411 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005412 if (FixedLM) {
5413 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5414 << LM.toString() << 0,
5415 getLocationOfByte(LM.getStart()),
5416 /*IsStringLocation*/true,
5417 getSpecifierRange(startSpecifier, specifierLen));
5418
5419 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5420 << FixedLM->toString()
5421 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5422
5423 } else {
5424 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5425 << LM.toString() << 0,
5426 getLocationOfByte(LM.getStart()),
5427 /*IsStringLocation*/true,
5428 getSpecifierRange(startSpecifier, specifierLen));
5429 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005430}
5431
5432void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5433 const analyze_format_string::ConversionSpecifier &CS,
5434 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005435 using namespace analyze_format_string;
5436
5437 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005438 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005439 if (FixedCS) {
5440 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5441 << CS.toString() << /*conversion specifier*/1,
5442 getLocationOfByte(CS.getStart()),
5443 /*IsStringLocation*/true,
5444 getSpecifierRange(startSpecifier, specifierLen));
5445
5446 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5447 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5448 << FixedCS->toString()
5449 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5450 } else {
5451 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5452 << CS.toString() << /*conversion specifier*/1,
5453 getLocationOfByte(CS.getStart()),
5454 /*IsStringLocation*/true,
5455 getSpecifierRange(startSpecifier, specifierLen));
5456 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005457}
5458
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005459void CheckFormatHandler::HandlePosition(const char *startPos,
5460 unsigned posLen) {
5461 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5462 getLocationOfByte(startPos),
5463 /*IsStringLocation*/true,
5464 getSpecifierRange(startPos, posLen));
5465}
5466
Ted Kremenekd1668192010-02-27 01:41:03 +00005467void
Ted Kremenek02087932010-07-16 02:11:22 +00005468CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5469 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5471 << (unsigned) p,
5472 getLocationOfByte(startPos), /*IsStringLocation*/true,
5473 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005474}
5475
Ted Kremenek02087932010-07-16 02:11:22 +00005476void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005477 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005478 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5479 getLocationOfByte(startPos),
5480 /*IsStringLocation*/true,
5481 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005482}
5483
Ted Kremenek02087932010-07-16 02:11:22 +00005484void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005485 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005486 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005487 EmitFormatDiagnostic(
5488 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5489 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5490 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005491 }
Ted Kremenek02087932010-07-16 02:11:22 +00005492}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005493
Jordan Rose58bbe422012-07-19 18:10:08 +00005494// Note that this may return NULL if there was an error parsing or building
5495// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005496const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005497 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005498}
5499
5500void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005501 // Does the number of data arguments exceed the number of
5502 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005503 if (!HasVAListArg) {
5504 // Find any arguments that weren't covered.
5505 CoveredArgs.flip();
5506 signed notCoveredArg = CoveredArgs.find_first();
5507 if (notCoveredArg >= 0) {
5508 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005509 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5510 } else {
5511 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005512 }
5513 }
5514}
5515
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005516void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5517 const Expr *ArgExpr) {
5518 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5519 "Invalid state");
5520
5521 if (!ArgExpr)
5522 return;
5523
5524 SourceLocation Loc = ArgExpr->getLocStart();
5525
5526 if (S.getSourceManager().isInSystemMacro(Loc))
5527 return;
5528
5529 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5530 for (auto E : DiagnosticExprs)
5531 PDiag << E->getSourceRange();
5532
5533 CheckFormatHandler::EmitFormatDiagnostic(
5534 S, IsFunctionCall, DiagnosticExprs[0],
5535 PDiag, Loc, /*IsStringLocation*/false,
5536 DiagnosticExprs[0]->getSourceRange());
5537}
5538
Ted Kremenekce815422010-07-19 21:25:57 +00005539bool
5540CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5541 SourceLocation Loc,
5542 const char *startSpec,
5543 unsigned specifierLen,
5544 const char *csStart,
5545 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005546 bool keepGoing = true;
5547 if (argIndex < NumDataArgs) {
5548 // Consider the argument coverered, even though the specifier doesn't
5549 // make sense.
5550 CoveredArgs.set(argIndex);
5551 }
5552 else {
5553 // If argIndex exceeds the number of data arguments we
5554 // don't issue a warning because that is just a cascade of warnings (and
5555 // they may have intended '%%' anyway). We don't want to continue processing
5556 // the format string after this point, however, as we will like just get
5557 // gibberish when trying to match arguments.
5558 keepGoing = false;
5559 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005560
5561 StringRef Specifier(csStart, csLen);
5562
5563 // If the specifier in non-printable, it could be the first byte of a UTF-8
5564 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5565 // hex value.
5566 std::string CodePointStr;
5567 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005568 llvm::UTF32 CodePoint;
5569 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5570 const llvm::UTF8 *E =
5571 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5572 llvm::ConversionResult Result =
5573 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005574
Justin Lebar90910552016-09-30 00:38:45 +00005575 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005576 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005577 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005578 }
5579
5580 llvm::raw_string_ostream OS(CodePointStr);
5581 if (CodePoint < 256)
5582 OS << "\\x" << llvm::format("%02x", CodePoint);
5583 else if (CodePoint <= 0xFFFF)
5584 OS << "\\u" << llvm::format("%04x", CodePoint);
5585 else
5586 OS << "\\U" << llvm::format("%08x", CodePoint);
5587 OS.flush();
5588 Specifier = CodePointStr;
5589 }
5590
5591 EmitFormatDiagnostic(
5592 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5593 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5594
Ted Kremenekce815422010-07-19 21:25:57 +00005595 return keepGoing;
5596}
5597
Richard Trieu03cf7b72011-10-28 00:41:25 +00005598void
5599CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5600 const char *startSpec,
5601 unsigned specifierLen) {
5602 EmitFormatDiagnostic(
5603 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5604 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5605}
5606
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005607bool
5608CheckFormatHandler::CheckNumArgs(
5609 const analyze_format_string::FormatSpecifier &FS,
5610 const analyze_format_string::ConversionSpecifier &CS,
5611 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5612
5613 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005614 PartialDiagnostic PDiag = FS.usesPositionalArg()
5615 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5616 << (argIndex+1) << NumDataArgs)
5617 : S.PDiag(diag::warn_printf_insufficient_data_args);
5618 EmitFormatDiagnostic(
5619 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5620 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005621
5622 // Since more arguments than conversion tokens are given, by extension
5623 // all arguments are covered, so mark this as so.
5624 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005625 return false;
5626 }
5627 return true;
5628}
5629
Richard Trieu03cf7b72011-10-28 00:41:25 +00005630template<typename Range>
5631void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5632 SourceLocation Loc,
5633 bool IsStringLocation,
5634 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005635 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005636 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005637 Loc, IsStringLocation, StringRange, FixIt);
5638}
5639
5640/// \brief If the format string is not within the funcion call, emit a note
5641/// so that the function call and string are in diagnostic messages.
5642///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005643/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005644/// call and only one diagnostic message will be produced. Otherwise, an
5645/// extra note will be emitted pointing to location of the format string.
5646///
5647/// \param ArgumentExpr the expression that is passed as the format string
5648/// argument in the function call. Used for getting locations when two
5649/// diagnostics are emitted.
5650///
5651/// \param PDiag the callee should already have provided any strings for the
5652/// diagnostic message. This function only adds locations and fixits
5653/// to diagnostics.
5654///
5655/// \param Loc primary location for diagnostic. If two diagnostics are
5656/// required, one will be at Loc and a new SourceLocation will be created for
5657/// the other one.
5658///
5659/// \param IsStringLocation if true, Loc points to the format string should be
5660/// used for the note. Otherwise, Loc points to the argument list and will
5661/// be used with PDiag.
5662///
5663/// \param StringRange some or all of the string to highlight. This is
5664/// templated so it can accept either a CharSourceRange or a SourceRange.
5665///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005666/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005667template <typename Range>
5668void CheckFormatHandler::EmitFormatDiagnostic(
5669 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5670 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5671 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005672 if (InFunctionCall) {
5673 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5674 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005675 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005676 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005677 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5678 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005679
5680 const Sema::SemaDiagnosticBuilder &Note =
5681 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5682 diag::note_format_string_defined);
5683
5684 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005685 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005686 }
5687}
5688
Ted Kremenek02087932010-07-16 02:11:22 +00005689//===--- CHECK: Printf format string checking ------------------------------===//
5690
5691namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005692
Ted Kremenek02087932010-07-16 02:11:22 +00005693class CheckPrintfHandler : public CheckFormatHandler {
5694public:
Stephen Hines648c3692016-09-16 01:07:04 +00005695 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005696 const Expr *origFormatExpr,
5697 const Sema::FormatStringType type, unsigned firstDataArg,
5698 unsigned numDataArgs, bool isObjC, const char *beg,
5699 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005700 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005701 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005702 llvm::SmallBitVector &CheckedVarArgs,
5703 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005704 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5705 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5706 inFunctionCall, CallType, CheckedVarArgs,
5707 UncoveredArg) {}
5708
5709 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5710
5711 /// Returns true if '%@' specifiers are allowed in the format string.
5712 bool allowsObjCArg() const {
5713 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5714 FSType == Sema::FST_OSTrace;
5715 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005716
Ted Kremenek02087932010-07-16 02:11:22 +00005717 bool HandleInvalidPrintfConversionSpecifier(
5718 const analyze_printf::PrintfSpecifier &FS,
5719 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005720 unsigned specifierLen) override;
5721
Ted Kremenek02087932010-07-16 02:11:22 +00005722 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5723 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005724 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005725 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5726 const char *StartSpecifier,
5727 unsigned SpecifierLen,
5728 const Expr *E);
5729
Ted Kremenek02087932010-07-16 02:11:22 +00005730 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5731 const char *startSpecifier, unsigned specifierLen);
5732 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5733 const analyze_printf::OptionalAmount &Amt,
5734 unsigned type,
5735 const char *startSpecifier, unsigned specifierLen);
5736 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5737 const analyze_printf::OptionalFlag &flag,
5738 const char *startSpecifier, unsigned specifierLen);
5739 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5740 const analyze_printf::OptionalFlag &ignoredFlag,
5741 const analyze_printf::OptionalFlag &flag,
5742 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005743 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005744 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005745
5746 void HandleEmptyObjCModifierFlag(const char *startFlag,
5747 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005748
Ted Kremenek2b417712015-07-02 05:39:16 +00005749 void HandleInvalidObjCModifierFlag(const char *startFlag,
5750 unsigned flagLen) override;
5751
5752 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5753 const char *flagsEnd,
5754 const char *conversionPosition)
5755 override;
5756};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005757
5758} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005759
5760bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5761 const analyze_printf::PrintfSpecifier &FS,
5762 const char *startSpecifier,
5763 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005764 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005765 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005766
Ted Kremenekce815422010-07-19 21:25:57 +00005767 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5768 getLocationOfByte(CS.getStart()),
5769 startSpecifier, specifierLen,
5770 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005771}
5772
Ted Kremenek02087932010-07-16 02:11:22 +00005773bool CheckPrintfHandler::HandleAmount(
5774 const analyze_format_string::OptionalAmount &Amt,
5775 unsigned k, const char *startSpecifier,
5776 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005777 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005778 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005779 unsigned argIndex = Amt.getArgIndex();
5780 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005781 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5782 << k,
5783 getLocationOfByte(Amt.getStart()),
5784 /*IsStringLocation*/true,
5785 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005786 // Don't do any more checking. We will just emit
5787 // spurious errors.
5788 return false;
5789 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005790
Ted Kremenek5739de72010-01-29 01:06:55 +00005791 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005792 // Although not in conformance with C99, we also allow the argument to be
5793 // an 'unsigned int' as that is a reasonably safe case. GCC also
5794 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005795 CoveredArgs.set(argIndex);
5796 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005797 if (!Arg)
5798 return false;
5799
Ted Kremenek5739de72010-01-29 01:06:55 +00005800 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005801
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005802 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5803 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005804
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005805 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005806 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005807 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005808 << T << Arg->getSourceRange(),
5809 getLocationOfByte(Amt.getStart()),
5810 /*IsStringLocation*/true,
5811 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005812 // Don't do any more checking. We will just emit
5813 // spurious errors.
5814 return false;
5815 }
5816 }
5817 }
5818 return true;
5819}
Ted Kremenek5739de72010-01-29 01:06:55 +00005820
Tom Careb49ec692010-06-17 19:00:27 +00005821void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005822 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005823 const analyze_printf::OptionalAmount &Amt,
5824 unsigned type,
5825 const char *startSpecifier,
5826 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005827 const analyze_printf::PrintfConversionSpecifier &CS =
5828 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005829
Richard Trieu03cf7b72011-10-28 00:41:25 +00005830 FixItHint fixit =
5831 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5832 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5833 Amt.getConstantLength()))
5834 : FixItHint();
5835
5836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5837 << type << CS.toString(),
5838 getLocationOfByte(Amt.getStart()),
5839 /*IsStringLocation*/true,
5840 getSpecifierRange(startSpecifier, specifierLen),
5841 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005842}
5843
Ted Kremenek02087932010-07-16 02:11:22 +00005844void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005845 const analyze_printf::OptionalFlag &flag,
5846 const char *startSpecifier,
5847 unsigned specifierLen) {
5848 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005849 const analyze_printf::PrintfConversionSpecifier &CS =
5850 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005851 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5852 << flag.toString() << CS.toString(),
5853 getLocationOfByte(flag.getPosition()),
5854 /*IsStringLocation*/true,
5855 getSpecifierRange(startSpecifier, specifierLen),
5856 FixItHint::CreateRemoval(
5857 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005858}
5859
5860void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005861 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005862 const analyze_printf::OptionalFlag &ignoredFlag,
5863 const analyze_printf::OptionalFlag &flag,
5864 const char *startSpecifier,
5865 unsigned specifierLen) {
5866 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005867 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5868 << ignoredFlag.toString() << flag.toString(),
5869 getLocationOfByte(ignoredFlag.getPosition()),
5870 /*IsStringLocation*/true,
5871 getSpecifierRange(startSpecifier, specifierLen),
5872 FixItHint::CreateRemoval(
5873 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005874}
5875
Ted Kremenek2b417712015-07-02 05:39:16 +00005876void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5877 unsigned flagLen) {
5878 // Warn about an empty flag.
5879 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5880 getLocationOfByte(startFlag),
5881 /*IsStringLocation*/true,
5882 getSpecifierRange(startFlag, flagLen));
5883}
5884
5885void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5886 unsigned flagLen) {
5887 // Warn about an invalid flag.
5888 auto Range = getSpecifierRange(startFlag, flagLen);
5889 StringRef flag(startFlag, flagLen);
5890 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5891 getLocationOfByte(startFlag),
5892 /*IsStringLocation*/true,
5893 Range, FixItHint::CreateRemoval(Range));
5894}
5895
5896void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5897 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5898 // Warn about using '[...]' without a '@' conversion.
5899 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5900 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5901 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5902 getLocationOfByte(conversionPosition),
5903 /*IsStringLocation*/true,
5904 Range, FixItHint::CreateRemoval(Range));
5905}
5906
Richard Smith55ce3522012-06-25 20:30:08 +00005907// Determines if the specified is a C++ class or struct containing
5908// a member with the specified name and kind (e.g. a CXXMethodDecl named
5909// "c_str()").
5910template<typename MemberKind>
5911static llvm::SmallPtrSet<MemberKind*, 1>
5912CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5913 const RecordType *RT = Ty->getAs<RecordType>();
5914 llvm::SmallPtrSet<MemberKind*, 1> Results;
5915
5916 if (!RT)
5917 return Results;
5918 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005919 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005920 return Results;
5921
Alp Tokerb6cc5922014-05-03 03:45:55 +00005922 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005923 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005924 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005925
5926 // We just need to include all members of the right kind turned up by the
5927 // filter, at this point.
5928 if (S.LookupQualifiedName(R, RT->getDecl()))
5929 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5930 NamedDecl *decl = (*I)->getUnderlyingDecl();
5931 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5932 Results.insert(FK);
5933 }
5934 return Results;
5935}
5936
Richard Smith2868a732014-02-28 01:36:39 +00005937/// Check if we could call '.c_str()' on an object.
5938///
5939/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5940/// allow the call, or if it would be ambiguous).
5941bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005942 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5943
Richard Smith2868a732014-02-28 01:36:39 +00005944 MethodSet Results =
5945 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5946 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5947 MI != ME; ++MI)
5948 if ((*MI)->getMinRequiredArguments() == 0)
5949 return true;
5950 return false;
5951}
5952
Richard Smith55ce3522012-06-25 20:30:08 +00005953// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005954// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005955// Returns true when a c_str() conversion method is found.
5956bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005957 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005958 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00005959
5960 MethodSet Results =
5961 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5962
5963 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5964 MI != ME; ++MI) {
5965 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005966 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005967 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005968 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005969 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005970 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5971 << "c_str()"
5972 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5973 return true;
5974 }
5975 }
5976
5977 return false;
5978}
5979
Ted Kremenekab278de2010-01-28 23:39:18 +00005980bool
Ted Kremenek02087932010-07-16 02:11:22 +00005981CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005982 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005983 const char *startSpecifier,
5984 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005985 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005986 using namespace analyze_printf;
5987
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005988 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005989
Ted Kremenek6cd69422010-07-19 22:01:06 +00005990 if (FS.consumesDataArgument()) {
5991 if (atFirstArg) {
5992 atFirstArg = false;
5993 usesPositionalArgs = FS.usesPositionalArg();
5994 }
5995 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005996 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5997 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005998 return false;
5999 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006000 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006001
Ted Kremenekd1668192010-02-27 01:41:03 +00006002 // First check if the field width, precision, and conversion specifier
6003 // have matching data arguments.
6004 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6005 startSpecifier, specifierLen)) {
6006 return false;
6007 }
6008
6009 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6010 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006011 return false;
6012 }
6013
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006014 if (!CS.consumesDataArgument()) {
6015 // FIXME: Technically specifying a precision or field width here
6016 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006017 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006018 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006019
Ted Kremenek4a49d982010-02-26 19:18:41 +00006020 // Consume the argument.
6021 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006022 if (argIndex < NumDataArgs) {
6023 // The check to see if the argIndex is valid will come later.
6024 // We set the bit here because we may exit early from this
6025 // function if we encounter some other error.
6026 CoveredArgs.set(argIndex);
6027 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006028
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006029 // FreeBSD kernel extensions.
6030 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6031 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6032 // We need at least two arguments.
6033 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6034 return false;
6035
6036 // Claim the second argument.
6037 CoveredArgs.set(argIndex + 1);
6038
6039 // Type check the first argument (int for %b, pointer for %D)
6040 const Expr *Ex = getDataArg(argIndex);
6041 const analyze_printf::ArgType &AT =
6042 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6043 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6044 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6045 EmitFormatDiagnostic(
6046 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6047 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6048 << false << Ex->getSourceRange(),
6049 Ex->getLocStart(), /*IsStringLocation*/false,
6050 getSpecifierRange(startSpecifier, specifierLen));
6051
6052 // Type check the second argument (char * for both %b and %D)
6053 Ex = getDataArg(argIndex + 1);
6054 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6055 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6056 EmitFormatDiagnostic(
6057 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6058 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6059 << false << Ex->getSourceRange(),
6060 Ex->getLocStart(), /*IsStringLocation*/false,
6061 getSpecifierRange(startSpecifier, specifierLen));
6062
6063 return true;
6064 }
6065
Ted Kremenek4a49d982010-02-26 19:18:41 +00006066 // Check for using an Objective-C specific conversion specifier
6067 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006068 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006069 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6070 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006071 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006072
Mehdi Amini06d367c2016-10-24 20:39:34 +00006073 // %P can only be used with os_log.
6074 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6075 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6076 specifierLen);
6077 }
6078
6079 // %n is not allowed with os_log.
6080 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6081 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6082 getLocationOfByte(CS.getStart()),
6083 /*IsStringLocation*/ false,
6084 getSpecifierRange(startSpecifier, specifierLen));
6085
6086 return true;
6087 }
6088
6089 // Only scalars are allowed for os_trace.
6090 if (FSType == Sema::FST_OSTrace &&
6091 (CS.getKind() == ConversionSpecifier::PArg ||
6092 CS.getKind() == ConversionSpecifier::sArg ||
6093 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6094 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6095 specifierLen);
6096 }
6097
6098 // Check for use of public/private annotation outside of os_log().
6099 if (FSType != Sema::FST_OSLog) {
6100 if (FS.isPublic().isSet()) {
6101 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6102 << "public",
6103 getLocationOfByte(FS.isPublic().getPosition()),
6104 /*IsStringLocation*/ false,
6105 getSpecifierRange(startSpecifier, specifierLen));
6106 }
6107 if (FS.isPrivate().isSet()) {
6108 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6109 << "private",
6110 getLocationOfByte(FS.isPrivate().getPosition()),
6111 /*IsStringLocation*/ false,
6112 getSpecifierRange(startSpecifier, specifierLen));
6113 }
6114 }
6115
Tom Careb49ec692010-06-17 19:00:27 +00006116 // Check for invalid use of field width
6117 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006118 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006119 startSpecifier, specifierLen);
6120 }
6121
6122 // Check for invalid use of precision
6123 if (!FS.hasValidPrecision()) {
6124 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6125 startSpecifier, specifierLen);
6126 }
6127
Mehdi Amini06d367c2016-10-24 20:39:34 +00006128 // Precision is mandatory for %P specifier.
6129 if (CS.getKind() == ConversionSpecifier::PArg &&
6130 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6131 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6132 getLocationOfByte(startSpecifier),
6133 /*IsStringLocation*/ false,
6134 getSpecifierRange(startSpecifier, specifierLen));
6135 }
6136
Tom Careb49ec692010-06-17 19:00:27 +00006137 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006138 if (!FS.hasValidThousandsGroupingPrefix())
6139 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006140 if (!FS.hasValidLeadingZeros())
6141 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6142 if (!FS.hasValidPlusPrefix())
6143 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006144 if (!FS.hasValidSpacePrefix())
6145 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006146 if (!FS.hasValidAlternativeForm())
6147 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6148 if (!FS.hasValidLeftJustified())
6149 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6150
6151 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006152 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6153 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6154 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006155 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6156 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6157 startSpecifier, specifierLen);
6158
6159 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006160 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006161 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6162 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006163 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006164 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006165 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006166 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6167 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006168
Jordan Rose92303592012-09-08 04:00:03 +00006169 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6170 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6171
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006172 // The remaining checks depend on the data arguments.
6173 if (HasVAListArg)
6174 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006175
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006176 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006177 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006178
Jordan Rose58bbe422012-07-19 18:10:08 +00006179 const Expr *Arg = getDataArg(argIndex);
6180 if (!Arg)
6181 return true;
6182
6183 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006184}
6185
Jordan Roseaee34382012-09-05 22:56:26 +00006186static bool requiresParensToAddCast(const Expr *E) {
6187 // FIXME: We should have a general way to reason about operator
6188 // precedence and whether parens are actually needed here.
6189 // Take care of a few common cases where they aren't.
6190 const Expr *Inside = E->IgnoreImpCasts();
6191 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6192 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6193
6194 switch (Inside->getStmtClass()) {
6195 case Stmt::ArraySubscriptExprClass:
6196 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006197 case Stmt::CharacterLiteralClass:
6198 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006199 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006200 case Stmt::FloatingLiteralClass:
6201 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006202 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006203 case Stmt::ObjCArrayLiteralClass:
6204 case Stmt::ObjCBoolLiteralExprClass:
6205 case Stmt::ObjCBoxedExprClass:
6206 case Stmt::ObjCDictionaryLiteralClass:
6207 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006208 case Stmt::ObjCIvarRefExprClass:
6209 case Stmt::ObjCMessageExprClass:
6210 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006211 case Stmt::ObjCStringLiteralClass:
6212 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006213 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006214 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006215 case Stmt::UnaryOperatorClass:
6216 return false;
6217 default:
6218 return true;
6219 }
6220}
6221
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006222static std::pair<QualType, StringRef>
6223shouldNotPrintDirectly(const ASTContext &Context,
6224 QualType IntendedTy,
6225 const Expr *E) {
6226 // Use a 'while' to peel off layers of typedefs.
6227 QualType TyTy = IntendedTy;
6228 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6229 StringRef Name = UserTy->getDecl()->getName();
6230 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006231 .Case("CFIndex", Context.getNSIntegerType())
6232 .Case("NSInteger", Context.getNSIntegerType())
6233 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006234 .Case("SInt32", Context.IntTy)
6235 .Case("UInt32", Context.UnsignedIntTy)
6236 .Default(QualType());
6237
6238 if (!CastTy.isNull())
6239 return std::make_pair(CastTy, Name);
6240
6241 TyTy = UserTy->desugar();
6242 }
6243
6244 // Strip parens if necessary.
6245 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6246 return shouldNotPrintDirectly(Context,
6247 PE->getSubExpr()->getType(),
6248 PE->getSubExpr());
6249
6250 // If this is a conditional expression, then its result type is constructed
6251 // via usual arithmetic conversions and thus there might be no necessary
6252 // typedef sugar there. Recurse to operands to check for NSInteger &
6253 // Co. usage condition.
6254 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6255 QualType TrueTy, FalseTy;
6256 StringRef TrueName, FalseName;
6257
6258 std::tie(TrueTy, TrueName) =
6259 shouldNotPrintDirectly(Context,
6260 CO->getTrueExpr()->getType(),
6261 CO->getTrueExpr());
6262 std::tie(FalseTy, FalseName) =
6263 shouldNotPrintDirectly(Context,
6264 CO->getFalseExpr()->getType(),
6265 CO->getFalseExpr());
6266
6267 if (TrueTy == FalseTy)
6268 return std::make_pair(TrueTy, TrueName);
6269 else if (TrueTy.isNull())
6270 return std::make_pair(FalseTy, FalseName);
6271 else if (FalseTy.isNull())
6272 return std::make_pair(TrueTy, TrueName);
6273 }
6274
6275 return std::make_pair(QualType(), StringRef());
6276}
6277
Richard Smith55ce3522012-06-25 20:30:08 +00006278bool
6279CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6280 const char *StartSpecifier,
6281 unsigned SpecifierLen,
6282 const Expr *E) {
6283 using namespace analyze_format_string;
6284 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006285
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006286 // Now type check the data expression that matches the
6287 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006288 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006289 if (!AT.isValid())
6290 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006291
Jordan Rose598ec092012-12-05 18:44:40 +00006292 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006293 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6294 ExprTy = TET->getUnderlyingExpr()->getType();
6295 }
6296
Seth Cantrellb4802962015-03-04 03:12:10 +00006297 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6298
6299 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006300 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006301 }
Jordan Rose98709982012-06-04 22:48:57 +00006302
Jordan Rose22b74712012-09-05 22:56:19 +00006303 // Look through argument promotions for our error message's reported type.
6304 // This includes the integral and floating promotions, but excludes array
6305 // and function pointer decay; seeing that an argument intended to be a
6306 // string has type 'char [6]' is probably more confusing than 'char *'.
6307 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6308 if (ICE->getCastKind() == CK_IntegralCast ||
6309 ICE->getCastKind() == CK_FloatingCast) {
6310 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006311 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006312
6313 // Check if we didn't match because of an implicit cast from a 'char'
6314 // or 'short' to an 'int'. This is done because printf is a varargs
6315 // function.
6316 if (ICE->getType() == S.Context.IntTy ||
6317 ICE->getType() == S.Context.UnsignedIntTy) {
6318 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006319 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006320 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006321 }
Jordan Rose98709982012-06-04 22:48:57 +00006322 }
Jordan Rose598ec092012-12-05 18:44:40 +00006323 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6324 // Special case for 'a', which has type 'int' in C.
6325 // Note, however, that we do /not/ want to treat multibyte constants like
6326 // 'MooV' as characters! This form is deprecated but still exists.
6327 if (ExprTy == S.Context.IntTy)
6328 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6329 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006330 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006331
Jordan Rosebc53ed12014-05-31 04:12:14 +00006332 // Look through enums to their underlying type.
6333 bool IsEnum = false;
6334 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6335 ExprTy = EnumTy->getDecl()->getIntegerType();
6336 IsEnum = true;
6337 }
6338
Jordan Rose0e5badd2012-12-05 18:44:49 +00006339 // %C in an Objective-C context prints a unichar, not a wchar_t.
6340 // If the argument is an integer of some kind, believe the %C and suggest
6341 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006342 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006343 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006344 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6345 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6346 !ExprTy->isCharType()) {
6347 // 'unichar' is defined as a typedef of unsigned short, but we should
6348 // prefer using the typedef if it is visible.
6349 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006350
6351 // While we are here, check if the value is an IntegerLiteral that happens
6352 // to be within the valid range.
6353 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6354 const llvm::APInt &V = IL->getValue();
6355 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6356 return true;
6357 }
6358
Jordan Rose0e5badd2012-12-05 18:44:49 +00006359 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6360 Sema::LookupOrdinaryName);
6361 if (S.LookupName(Result, S.getCurScope())) {
6362 NamedDecl *ND = Result.getFoundDecl();
6363 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6364 if (TD->getUnderlyingType() == IntendedTy)
6365 IntendedTy = S.Context.getTypedefType(TD);
6366 }
6367 }
6368 }
6369
6370 // Special-case some of Darwin's platform-independence types by suggesting
6371 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006372 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006373 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006374 QualType CastTy;
6375 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6376 if (!CastTy.isNull()) {
6377 IntendedTy = CastTy;
6378 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006379 }
6380 }
6381
Jordan Rose22b74712012-09-05 22:56:19 +00006382 // We may be able to offer a FixItHint if it is a supported type.
6383 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006384 bool success =
6385 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006386
Jordan Rose22b74712012-09-05 22:56:19 +00006387 if (success) {
6388 // Get the fix string from the fixed format specifier
6389 SmallString<16> buf;
6390 llvm::raw_svector_ostream os(buf);
6391 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006392
Jordan Roseaee34382012-09-05 22:56:26 +00006393 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6394
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006395 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006396 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6397 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6398 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6399 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006400 // In this case, the specifier is wrong and should be changed to match
6401 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006402 EmitFormatDiagnostic(S.PDiag(diag)
6403 << AT.getRepresentativeTypeName(S.Context)
6404 << IntendedTy << IsEnum << E->getSourceRange(),
6405 E->getLocStart(),
6406 /*IsStringLocation*/ false, SpecRange,
6407 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006408 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006409 // The canonical type for formatting this value is different from the
6410 // actual type of the expression. (This occurs, for example, with Darwin's
6411 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6412 // should be printed as 'long' for 64-bit compatibility.)
6413 // Rather than emitting a normal format/argument mismatch, we want to
6414 // add a cast to the recommended type (and correct the format string
6415 // if necessary).
6416 SmallString<16> CastBuf;
6417 llvm::raw_svector_ostream CastFix(CastBuf);
6418 CastFix << "(";
6419 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6420 CastFix << ")";
6421
6422 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006423 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006424 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6425
6426 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6427 // If there's already a cast present, just replace it.
6428 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6429 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6430
6431 } else if (!requiresParensToAddCast(E)) {
6432 // If the expression has high enough precedence,
6433 // just write the C-style cast.
6434 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6435 CastFix.str()));
6436 } else {
6437 // Otherwise, add parens around the expression as well as the cast.
6438 CastFix << "(";
6439 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6440 CastFix.str()));
6441
Alp Tokerb6cc5922014-05-03 03:45:55 +00006442 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006443 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6444 }
6445
Jordan Rose0e5badd2012-12-05 18:44:49 +00006446 if (ShouldNotPrintDirectly) {
6447 // The expression has a type that should not be printed directly.
6448 // We extract the name from the typedef because we don't want to show
6449 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006450 StringRef Name;
6451 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6452 Name = TypedefTy->getDecl()->getName();
6453 else
6454 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006455 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006456 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006457 << E->getSourceRange(),
6458 E->getLocStart(), /*IsStringLocation=*/false,
6459 SpecRange, Hints);
6460 } else {
6461 // In this case, the expression could be printed using a different
6462 // specifier, but we've decided that the specifier is probably correct
6463 // and we should cast instead. Just use the normal warning message.
6464 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006465 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6466 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006467 << E->getSourceRange(),
6468 E->getLocStart(), /*IsStringLocation*/false,
6469 SpecRange, Hints);
6470 }
Jordan Roseaee34382012-09-05 22:56:26 +00006471 }
Jordan Rose22b74712012-09-05 22:56:19 +00006472 } else {
6473 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6474 SpecifierLen);
6475 // Since the warning for passing non-POD types to variadic functions
6476 // was deferred until now, we emit a warning for non-POD
6477 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006478 switch (S.isValidVarArgType(ExprTy)) {
6479 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006480 case Sema::VAK_ValidInCXX11: {
6481 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6482 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6483 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6484 }
Richard Smithd7293d72013-08-05 18:49:43 +00006485
Seth Cantrellb4802962015-03-04 03:12:10 +00006486 EmitFormatDiagnostic(
6487 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6488 << IsEnum << CSR << E->getSourceRange(),
6489 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6490 break;
6491 }
Richard Smithd7293d72013-08-05 18:49:43 +00006492 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006493 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006494 EmitFormatDiagnostic(
6495 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006496 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006497 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006498 << CallType
6499 << AT.getRepresentativeTypeName(S.Context)
6500 << CSR
6501 << E->getSourceRange(),
6502 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006503 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006504 break;
6505
6506 case Sema::VAK_Invalid:
6507 if (ExprTy->isObjCObjectType())
6508 EmitFormatDiagnostic(
6509 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6510 << S.getLangOpts().CPlusPlus11
6511 << ExprTy
6512 << CallType
6513 << AT.getRepresentativeTypeName(S.Context)
6514 << CSR
6515 << E->getSourceRange(),
6516 E->getLocStart(), /*IsStringLocation*/false, CSR);
6517 else
6518 // FIXME: If this is an initializer list, suggest removing the braces
6519 // or inserting a cast to the target type.
6520 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6521 << isa<InitListExpr>(E) << ExprTy << CallType
6522 << AT.getRepresentativeTypeName(S.Context)
6523 << E->getSourceRange();
6524 break;
6525 }
6526
6527 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6528 "format string specifier index out of range");
6529 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006530 }
6531
Ted Kremenekab278de2010-01-28 23:39:18 +00006532 return true;
6533}
6534
Ted Kremenek02087932010-07-16 02:11:22 +00006535//===--- CHECK: Scanf format string checking ------------------------------===//
6536
6537namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006538
Ted Kremenek02087932010-07-16 02:11:22 +00006539class CheckScanfHandler : public CheckFormatHandler {
6540public:
Stephen Hines648c3692016-09-16 01:07:04 +00006541 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006542 const Expr *origFormatExpr, Sema::FormatStringType type,
6543 unsigned firstDataArg, unsigned numDataArgs,
6544 const char *beg, bool hasVAListArg,
6545 ArrayRef<const Expr *> Args, unsigned formatIdx,
6546 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006547 llvm::SmallBitVector &CheckedVarArgs,
6548 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006549 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6550 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6551 inFunctionCall, CallType, CheckedVarArgs,
6552 UncoveredArg) {}
6553
Ted Kremenek02087932010-07-16 02:11:22 +00006554 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6555 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006556 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006557
6558 bool HandleInvalidScanfConversionSpecifier(
6559 const analyze_scanf::ScanfSpecifier &FS,
6560 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006561 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006562
Craig Toppere14c0f82014-03-12 04:55:44 +00006563 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006564};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006565
6566} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006567
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006568void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6569 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006570 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6571 getLocationOfByte(end), /*IsStringLocation*/true,
6572 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006573}
6574
Ted Kremenekce815422010-07-19 21:25:57 +00006575bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6576 const analyze_scanf::ScanfSpecifier &FS,
6577 const char *startSpecifier,
6578 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006579 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006580 FS.getConversionSpecifier();
6581
6582 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6583 getLocationOfByte(CS.getStart()),
6584 startSpecifier, specifierLen,
6585 CS.getStart(), CS.getLength());
6586}
6587
Ted Kremenek02087932010-07-16 02:11:22 +00006588bool CheckScanfHandler::HandleScanfSpecifier(
6589 const analyze_scanf::ScanfSpecifier &FS,
6590 const char *startSpecifier,
6591 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006592 using namespace analyze_scanf;
6593 using namespace analyze_format_string;
6594
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006595 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006596
Ted Kremenek6cd69422010-07-19 22:01:06 +00006597 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6598 // be used to decide if we are using positional arguments consistently.
6599 if (FS.consumesDataArgument()) {
6600 if (atFirstArg) {
6601 atFirstArg = false;
6602 usesPositionalArgs = FS.usesPositionalArg();
6603 }
6604 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006605 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6606 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006607 return false;
6608 }
Ted Kremenek02087932010-07-16 02:11:22 +00006609 }
6610
6611 // Check if the field with is non-zero.
6612 const OptionalAmount &Amt = FS.getFieldWidth();
6613 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6614 if (Amt.getConstantAmount() == 0) {
6615 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6616 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006617 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6618 getLocationOfByte(Amt.getStart()),
6619 /*IsStringLocation*/true, R,
6620 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006621 }
6622 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006623
Ted Kremenek02087932010-07-16 02:11:22 +00006624 if (!FS.consumesDataArgument()) {
6625 // FIXME: Technically specifying a precision or field width here
6626 // makes no sense. Worth issuing a warning at some point.
6627 return true;
6628 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006629
Ted Kremenek02087932010-07-16 02:11:22 +00006630 // Consume the argument.
6631 unsigned argIndex = FS.getArgIndex();
6632 if (argIndex < NumDataArgs) {
6633 // The check to see if the argIndex is valid will come later.
6634 // We set the bit here because we may exit early from this
6635 // function if we encounter some other error.
6636 CoveredArgs.set(argIndex);
6637 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006638
Ted Kremenek4407ea42010-07-20 20:04:47 +00006639 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006640 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006641 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6642 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006643 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006644 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006645 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006646 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6647 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006648
Jordan Rose92303592012-09-08 04:00:03 +00006649 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6650 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6651
Ted Kremenek02087932010-07-16 02:11:22 +00006652 // The remaining checks depend on the data arguments.
6653 if (HasVAListArg)
6654 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006655
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006656 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006657 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006658
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006659 // Check that the argument type matches the format specifier.
6660 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006661 if (!Ex)
6662 return true;
6663
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006664 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006665
6666 if (!AT.isValid()) {
6667 return true;
6668 }
6669
Seth Cantrellb4802962015-03-04 03:12:10 +00006670 analyze_format_string::ArgType::MatchKind match =
6671 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006672 if (match == analyze_format_string::ArgType::Match) {
6673 return true;
6674 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006675
Seth Cantrell79340072015-03-04 05:58:08 +00006676 ScanfSpecifier fixedFS = FS;
6677 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6678 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006679
Seth Cantrell79340072015-03-04 05:58:08 +00006680 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6681 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6682 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6683 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006684
Seth Cantrell79340072015-03-04 05:58:08 +00006685 if (success) {
6686 // Get the fix string from the fixed format specifier.
6687 SmallString<128> buf;
6688 llvm::raw_svector_ostream os(buf);
6689 fixedFS.toString(os);
6690
6691 EmitFormatDiagnostic(
6692 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6693 << Ex->getType() << false << Ex->getSourceRange(),
6694 Ex->getLocStart(),
6695 /*IsStringLocation*/ false,
6696 getSpecifierRange(startSpecifier, specifierLen),
6697 FixItHint::CreateReplacement(
6698 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6699 } else {
6700 EmitFormatDiagnostic(S.PDiag(diag)
6701 << AT.getRepresentativeTypeName(S.Context)
6702 << Ex->getType() << false << Ex->getSourceRange(),
6703 Ex->getLocStart(),
6704 /*IsStringLocation*/ false,
6705 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006706 }
6707
Ted Kremenek02087932010-07-16 02:11:22 +00006708 return true;
6709}
6710
Stephen Hines648c3692016-09-16 01:07:04 +00006711static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006712 const Expr *OrigFormatExpr,
6713 ArrayRef<const Expr *> Args,
6714 bool HasVAListArg, unsigned format_idx,
6715 unsigned firstDataArg,
6716 Sema::FormatStringType Type,
6717 bool inFunctionCall,
6718 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006719 llvm::SmallBitVector &CheckedVarArgs,
6720 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006721 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006722 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006723 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006724 S, inFunctionCall, Args[format_idx],
6725 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006726 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006727 return;
6728 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006729
Ted Kremenekab278de2010-01-28 23:39:18 +00006730 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006731 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006732 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006733 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006734 const ConstantArrayType *T =
6735 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006736 assert(T && "String literal not of constant array type!");
6737 size_t TypeSize = T->getSize().getZExtValue();
6738 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006739 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006740
6741 // Emit a warning if the string literal is truncated and does not contain an
6742 // embedded null character.
6743 if (TypeSize <= StrRef.size() &&
6744 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6745 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006746 S, inFunctionCall, Args[format_idx],
6747 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006748 FExpr->getLocStart(),
6749 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6750 return;
6751 }
6752
Ted Kremenekab278de2010-01-28 23:39:18 +00006753 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006754 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006755 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006756 S, inFunctionCall, Args[format_idx],
6757 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006758 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006759 return;
6760 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006761
6762 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006763 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6764 Type == Sema::FST_OSTrace) {
6765 CheckPrintfHandler H(
6766 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6767 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6768 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6769 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006770
Hans Wennborg23926bd2011-12-15 10:25:47 +00006771 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006772 S.getLangOpts(),
6773 S.Context.getTargetInfo(),
6774 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006775 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006776 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006777 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6778 numDataArgs, Str, HasVAListArg, Args, format_idx,
6779 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006780
Hans Wennborg23926bd2011-12-15 10:25:47 +00006781 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006782 S.getLangOpts(),
6783 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006784 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006785 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006786}
6787
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006788bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6789 // Str - The format string. NOTE: this is NOT null-terminated!
6790 StringRef StrRef = FExpr->getString();
6791 const char *Str = StrRef.data();
6792 // Account for cases where the string literal is truncated in a declaration.
6793 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6794 assert(T && "String literal not of constant array type!");
6795 size_t TypeSize = T->getSize().getZExtValue();
6796 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6797 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6798 getLangOpts(),
6799 Context.getTargetInfo());
6800}
6801
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006802//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6803
6804// Returns the related absolute value function that is larger, of 0 if one
6805// does not exist.
6806static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6807 switch (AbsFunction) {
6808 default:
6809 return 0;
6810
6811 case Builtin::BI__builtin_abs:
6812 return Builtin::BI__builtin_labs;
6813 case Builtin::BI__builtin_labs:
6814 return Builtin::BI__builtin_llabs;
6815 case Builtin::BI__builtin_llabs:
6816 return 0;
6817
6818 case Builtin::BI__builtin_fabsf:
6819 return Builtin::BI__builtin_fabs;
6820 case Builtin::BI__builtin_fabs:
6821 return Builtin::BI__builtin_fabsl;
6822 case Builtin::BI__builtin_fabsl:
6823 return 0;
6824
6825 case Builtin::BI__builtin_cabsf:
6826 return Builtin::BI__builtin_cabs;
6827 case Builtin::BI__builtin_cabs:
6828 return Builtin::BI__builtin_cabsl;
6829 case Builtin::BI__builtin_cabsl:
6830 return 0;
6831
6832 case Builtin::BIabs:
6833 return Builtin::BIlabs;
6834 case Builtin::BIlabs:
6835 return Builtin::BIllabs;
6836 case Builtin::BIllabs:
6837 return 0;
6838
6839 case Builtin::BIfabsf:
6840 return Builtin::BIfabs;
6841 case Builtin::BIfabs:
6842 return Builtin::BIfabsl;
6843 case Builtin::BIfabsl:
6844 return 0;
6845
6846 case Builtin::BIcabsf:
6847 return Builtin::BIcabs;
6848 case Builtin::BIcabs:
6849 return Builtin::BIcabsl;
6850 case Builtin::BIcabsl:
6851 return 0;
6852 }
6853}
6854
6855// Returns the argument type of the absolute value function.
6856static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6857 unsigned AbsType) {
6858 if (AbsType == 0)
6859 return QualType();
6860
6861 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6862 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6863 if (Error != ASTContext::GE_None)
6864 return QualType();
6865
6866 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6867 if (!FT)
6868 return QualType();
6869
6870 if (FT->getNumParams() != 1)
6871 return QualType();
6872
6873 return FT->getParamType(0);
6874}
6875
6876// Returns the best absolute value function, or zero, based on type and
6877// current absolute value function.
6878static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6879 unsigned AbsFunctionKind) {
6880 unsigned BestKind = 0;
6881 uint64_t ArgSize = Context.getTypeSize(ArgType);
6882 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6883 Kind = getLargerAbsoluteValueFunction(Kind)) {
6884 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6885 if (Context.getTypeSize(ParamType) >= ArgSize) {
6886 if (BestKind == 0)
6887 BestKind = Kind;
6888 else if (Context.hasSameType(ParamType, ArgType)) {
6889 BestKind = Kind;
6890 break;
6891 }
6892 }
6893 }
6894 return BestKind;
6895}
6896
6897enum AbsoluteValueKind {
6898 AVK_Integer,
6899 AVK_Floating,
6900 AVK_Complex
6901};
6902
6903static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6904 if (T->isIntegralOrEnumerationType())
6905 return AVK_Integer;
6906 if (T->isRealFloatingType())
6907 return AVK_Floating;
6908 if (T->isAnyComplexType())
6909 return AVK_Complex;
6910
6911 llvm_unreachable("Type not integer, floating, or complex");
6912}
6913
6914// Changes the absolute value function to a different type. Preserves whether
6915// the function is a builtin.
6916static unsigned changeAbsFunction(unsigned AbsKind,
6917 AbsoluteValueKind ValueKind) {
6918 switch (ValueKind) {
6919 case AVK_Integer:
6920 switch (AbsKind) {
6921 default:
6922 return 0;
6923 case Builtin::BI__builtin_fabsf:
6924 case Builtin::BI__builtin_fabs:
6925 case Builtin::BI__builtin_fabsl:
6926 case Builtin::BI__builtin_cabsf:
6927 case Builtin::BI__builtin_cabs:
6928 case Builtin::BI__builtin_cabsl:
6929 return Builtin::BI__builtin_abs;
6930 case Builtin::BIfabsf:
6931 case Builtin::BIfabs:
6932 case Builtin::BIfabsl:
6933 case Builtin::BIcabsf:
6934 case Builtin::BIcabs:
6935 case Builtin::BIcabsl:
6936 return Builtin::BIabs;
6937 }
6938 case AVK_Floating:
6939 switch (AbsKind) {
6940 default:
6941 return 0;
6942 case Builtin::BI__builtin_abs:
6943 case Builtin::BI__builtin_labs:
6944 case Builtin::BI__builtin_llabs:
6945 case Builtin::BI__builtin_cabsf:
6946 case Builtin::BI__builtin_cabs:
6947 case Builtin::BI__builtin_cabsl:
6948 return Builtin::BI__builtin_fabsf;
6949 case Builtin::BIabs:
6950 case Builtin::BIlabs:
6951 case Builtin::BIllabs:
6952 case Builtin::BIcabsf:
6953 case Builtin::BIcabs:
6954 case Builtin::BIcabsl:
6955 return Builtin::BIfabsf;
6956 }
6957 case AVK_Complex:
6958 switch (AbsKind) {
6959 default:
6960 return 0;
6961 case Builtin::BI__builtin_abs:
6962 case Builtin::BI__builtin_labs:
6963 case Builtin::BI__builtin_llabs:
6964 case Builtin::BI__builtin_fabsf:
6965 case Builtin::BI__builtin_fabs:
6966 case Builtin::BI__builtin_fabsl:
6967 return Builtin::BI__builtin_cabsf;
6968 case Builtin::BIabs:
6969 case Builtin::BIlabs:
6970 case Builtin::BIllabs:
6971 case Builtin::BIfabsf:
6972 case Builtin::BIfabs:
6973 case Builtin::BIfabsl:
6974 return Builtin::BIcabsf;
6975 }
6976 }
6977 llvm_unreachable("Unable to convert function");
6978}
6979
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006980static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006981 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6982 if (!FnInfo)
6983 return 0;
6984
6985 switch (FDecl->getBuiltinID()) {
6986 default:
6987 return 0;
6988 case Builtin::BI__builtin_abs:
6989 case Builtin::BI__builtin_fabs:
6990 case Builtin::BI__builtin_fabsf:
6991 case Builtin::BI__builtin_fabsl:
6992 case Builtin::BI__builtin_labs:
6993 case Builtin::BI__builtin_llabs:
6994 case Builtin::BI__builtin_cabs:
6995 case Builtin::BI__builtin_cabsf:
6996 case Builtin::BI__builtin_cabsl:
6997 case Builtin::BIabs:
6998 case Builtin::BIlabs:
6999 case Builtin::BIllabs:
7000 case Builtin::BIfabs:
7001 case Builtin::BIfabsf:
7002 case Builtin::BIfabsl:
7003 case Builtin::BIcabs:
7004 case Builtin::BIcabsf:
7005 case Builtin::BIcabsl:
7006 return FDecl->getBuiltinID();
7007 }
7008 llvm_unreachable("Unknown Builtin type");
7009}
7010
7011// If the replacement is valid, emit a note with replacement function.
7012// Additionally, suggest including the proper header if not already included.
7013static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007014 unsigned AbsKind, QualType ArgType) {
7015 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007016 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007017 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007018 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7019 FunctionName = "std::abs";
7020 if (ArgType->isIntegralOrEnumerationType()) {
7021 HeaderName = "cstdlib";
7022 } else if (ArgType->isRealFloatingType()) {
7023 HeaderName = "cmath";
7024 } else {
7025 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007026 }
Richard Trieubeffb832014-04-15 23:47:53 +00007027
7028 // Lookup all std::abs
7029 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007030 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007031 R.suppressDiagnostics();
7032 S.LookupQualifiedName(R, Std);
7033
7034 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007035 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007036 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7037 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7038 } else {
7039 FDecl = dyn_cast<FunctionDecl>(I);
7040 }
7041 if (!FDecl)
7042 continue;
7043
7044 // Found std::abs(), check that they are the right ones.
7045 if (FDecl->getNumParams() != 1)
7046 continue;
7047
7048 // Check that the parameter type can handle the argument.
7049 QualType ParamType = FDecl->getParamDecl(0)->getType();
7050 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7051 S.Context.getTypeSize(ArgType) <=
7052 S.Context.getTypeSize(ParamType)) {
7053 // Found a function, don't need the header hint.
7054 EmitHeaderHint = false;
7055 break;
7056 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007057 }
Richard Trieubeffb832014-04-15 23:47:53 +00007058 }
7059 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007060 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007061 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7062
7063 if (HeaderName) {
7064 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7065 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7066 R.suppressDiagnostics();
7067 S.LookupName(R, S.getCurScope());
7068
7069 if (R.isSingleResult()) {
7070 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7071 if (FD && FD->getBuiltinID() == AbsKind) {
7072 EmitHeaderHint = false;
7073 } else {
7074 return;
7075 }
7076 } else if (!R.empty()) {
7077 return;
7078 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007079 }
7080 }
7081
7082 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007083 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007084
Richard Trieubeffb832014-04-15 23:47:53 +00007085 if (!HeaderName)
7086 return;
7087
7088 if (!EmitHeaderHint)
7089 return;
7090
Alp Toker5d96e0a2014-07-11 20:53:51 +00007091 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7092 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007093}
7094
Richard Trieua7f30b12016-12-06 01:42:28 +00007095template <std::size_t StrLen>
7096static bool IsStdFunction(const FunctionDecl *FDecl,
7097 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007098 if (!FDecl)
7099 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007100 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007101 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007102 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007103 return false;
7104
7105 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007106}
7107
7108// Warn when using the wrong abs() function.
7109void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007110 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007111 if (Call->getNumArgs() != 1)
7112 return;
7113
7114 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007115 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007116 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007117 return;
7118
7119 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7120 QualType ParamType = Call->getArg(0)->getType();
7121
Alp Toker5d96e0a2014-07-11 20:53:51 +00007122 // Unsigned types cannot be negative. Suggest removing the absolute value
7123 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007124 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007125 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007126 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007127 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7128 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007129 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007130 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7131 return;
7132 }
7133
David Majnemer7f77eb92015-11-15 03:04:34 +00007134 // Taking the absolute value of a pointer is very suspicious, they probably
7135 // wanted to index into an array, dereference a pointer, call a function, etc.
7136 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7137 unsigned DiagType = 0;
7138 if (ArgType->isFunctionType())
7139 DiagType = 1;
7140 else if (ArgType->isArrayType())
7141 DiagType = 2;
7142
7143 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7144 return;
7145 }
7146
Richard Trieubeffb832014-04-15 23:47:53 +00007147 // std::abs has overloads which prevent most of the absolute value problems
7148 // from occurring.
7149 if (IsStdAbs)
7150 return;
7151
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007152 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7153 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7154
7155 // The argument and parameter are the same kind. Check if they are the right
7156 // size.
7157 if (ArgValueKind == ParamValueKind) {
7158 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7159 return;
7160
7161 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7162 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7163 << FDecl << ArgType << ParamType;
7164
7165 if (NewAbsKind == 0)
7166 return;
7167
7168 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007169 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007170 return;
7171 }
7172
7173 // ArgValueKind != ParamValueKind
7174 // The wrong type of absolute value function was used. Attempt to find the
7175 // proper one.
7176 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7177 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7178 if (NewAbsKind == 0)
7179 return;
7180
7181 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7182 << FDecl << ParamValueKind << ArgValueKind;
7183
7184 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007185 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007186}
7187
Richard Trieu67c00712016-12-05 23:41:46 +00007188//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007189void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7190 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007191 if (!Call || !FDecl) return;
7192
7193 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007194 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007195 if (Call->getExprLoc().isMacroID()) return;
7196
7197 // Only care about the one template argument, two function parameter std::max
7198 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007199 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007200 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7201 if (!ArgList) return;
7202 if (ArgList->size() != 1) return;
7203
7204 // Check that template type argument is unsigned integer.
7205 const auto& TA = ArgList->get(0);
7206 if (TA.getKind() != TemplateArgument::Type) return;
7207 QualType ArgType = TA.getAsType();
7208 if (!ArgType->isUnsignedIntegerType()) return;
7209
7210 // See if either argument is a literal zero.
7211 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7212 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7213 if (!MTE) return false;
7214 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7215 if (!Num) return false;
7216 if (Num->getValue() != 0) return false;
7217 return true;
7218 };
7219
7220 const Expr *FirstArg = Call->getArg(0);
7221 const Expr *SecondArg = Call->getArg(1);
7222 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7223 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7224
7225 // Only warn when exactly one argument is zero.
7226 if (IsFirstArgZero == IsSecondArgZero) return;
7227
7228 SourceRange FirstRange = FirstArg->getSourceRange();
7229 SourceRange SecondRange = SecondArg->getSourceRange();
7230
7231 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7232
7233 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7234 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7235
7236 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7237 SourceRange RemovalRange;
7238 if (IsFirstArgZero) {
7239 RemovalRange = SourceRange(FirstRange.getBegin(),
7240 SecondRange.getBegin().getLocWithOffset(-1));
7241 } else {
7242 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7243 SecondRange.getEnd());
7244 }
7245
7246 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7247 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7248 << FixItHint::CreateRemoval(RemovalRange);
7249}
7250
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007251//===--- CHECK: Standard memory functions ---------------------------------===//
7252
Nico Weber0e6daef2013-12-26 23:38:39 +00007253/// \brief Takes the expression passed to the size_t parameter of functions
7254/// such as memcmp, strncat, etc and warns if it's a comparison.
7255///
7256/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7257static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7258 IdentifierInfo *FnName,
7259 SourceLocation FnLoc,
7260 SourceLocation RParenLoc) {
7261 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7262 if (!Size)
7263 return false;
7264
Richard Smithc70f1d62017-12-14 15:16:18 +00007265 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7266 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007267 return false;
7268
Nico Weber0e6daef2013-12-26 23:38:39 +00007269 SourceRange SizeRange = Size->getSourceRange();
7270 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7271 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007272 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007273 << FnName << FixItHint::CreateInsertion(
7274 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007275 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007276 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007277 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007278 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7279 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007280
7281 return true;
7282}
7283
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007284/// \brief Determine whether the given type is or contains a dynamic class type
7285/// (e.g., whether it has a vtable).
7286static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7287 bool &IsContained) {
7288 // Look through array types while ignoring qualifiers.
7289 const Type *Ty = T->getBaseElementTypeUnsafe();
7290 IsContained = false;
7291
7292 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7293 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007294 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007295 return nullptr;
7296
7297 if (RD->isDynamicClass())
7298 return RD;
7299
7300 // Check all the fields. If any bases were dynamic, the class is dynamic.
7301 // It's impossible for a class to transitively contain itself by value, so
7302 // infinite recursion is impossible.
7303 for (auto *FD : RD->fields()) {
7304 bool SubContained;
7305 if (const CXXRecordDecl *ContainedRD =
7306 getContainedDynamicClass(FD->getType(), SubContained)) {
7307 IsContained = true;
7308 return ContainedRD;
7309 }
7310 }
7311
7312 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007313}
7314
Chandler Carruth889ed862011-06-21 23:04:20 +00007315/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007316/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007317static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007318 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007319 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007320 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007321 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007322
Craig Topperc3ec1492014-05-26 06:22:03 +00007323 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007324}
7325
Chandler Carruth889ed862011-06-21 23:04:20 +00007326/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007327static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007328 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7329 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007330 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007331 return SizeOf->getTypeOfArgument();
7332
7333 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007334}
7335
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007336/// \brief Check for dangerous or invalid arguments to memset().
7337///
Chandler Carruthac687262011-06-03 06:23:57 +00007338/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007339/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7340/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007341///
7342/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007343void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007344 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007345 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007346 assert(BId != 0);
7347
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007348 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007349 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007350 unsigned ExpectedNumArgs =
7351 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007352 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007353 return;
7354
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007355 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007356 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007357 unsigned LenArg =
7358 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007359 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007360
Nico Weber0e6daef2013-12-26 23:38:39 +00007361 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7362 Call->getLocStart(), Call->getRParenLoc()))
7363 return;
7364
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007365 // We have special checking when the length is a sizeof expression.
7366 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7367 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7368 llvm::FoldingSetNodeID SizeOfArgID;
7369
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007370 // Although widely used, 'bzero' is not a standard function. Be more strict
7371 // with the argument types before allowing diagnostics and only allow the
7372 // form bzero(ptr, sizeof(...)).
7373 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7374 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7375 return;
7376
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007377 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7378 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007379 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007380
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007381 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007382 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007383 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007384 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007385
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007386 // Never warn about void type pointers. This can be used to suppress
7387 // false positives.
7388 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007389 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007390
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007391 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7392 // actually comparing the expressions for equality. Because computing the
7393 // expression IDs can be expensive, we only do this if the diagnostic is
7394 // enabled.
7395 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007396 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7397 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007398 // We only compute IDs for expressions if the warning is enabled, and
7399 // cache the sizeof arg's ID.
7400 if (SizeOfArgID == llvm::FoldingSetNodeID())
7401 SizeOfArg->Profile(SizeOfArgID, Context, true);
7402 llvm::FoldingSetNodeID DestID;
7403 Dest->Profile(DestID, Context, true);
7404 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007405 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7406 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007407 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007408 StringRef ReadableName = FnName->getName();
7409
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007410 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007411 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007412 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007413 if (!PointeeTy->isIncompleteType() &&
7414 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007415 ActionIdx = 2; // If the pointee's size is sizeof(char),
7416 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007417
7418 // If the function is defined as a builtin macro, do not show macro
7419 // expansion.
7420 SourceLocation SL = SizeOfArg->getExprLoc();
7421 SourceRange DSR = Dest->getSourceRange();
7422 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007423 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007424
7425 if (SM.isMacroArgExpansion(SL)) {
7426 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7427 SL = SM.getSpellingLoc(SL);
7428 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7429 SM.getSpellingLoc(DSR.getEnd()));
7430 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7431 SM.getSpellingLoc(SSR.getEnd()));
7432 }
7433
Anna Zaksd08d9152012-05-30 23:14:52 +00007434 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007435 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007436 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007437 << PointeeTy
7438 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007439 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007440 << SSR);
7441 DiagRuntimeBehavior(SL, SizeOfArg,
7442 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7443 << ActionIdx
7444 << SSR);
7445
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007446 break;
7447 }
7448 }
7449
7450 // Also check for cases where the sizeof argument is the exact same
7451 // type as the memory argument, and where it points to a user-defined
7452 // record type.
7453 if (SizeOfArgTy != QualType()) {
7454 if (PointeeTy->isRecordType() &&
7455 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7456 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7457 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7458 << FnName << SizeOfArgTy << ArgIdx
7459 << PointeeTy << Dest->getSourceRange()
7460 << LenExpr->getSourceRange());
7461 break;
7462 }
Nico Weberc5e73862011-06-14 16:14:58 +00007463 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007464 } else if (DestTy->isArrayType()) {
7465 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007466 }
Nico Weberc5e73862011-06-14 16:14:58 +00007467
Nico Weberc44b35e2015-03-21 17:37:46 +00007468 if (PointeeTy == QualType())
7469 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007470
Nico Weberc44b35e2015-03-21 17:37:46 +00007471 // Always complain about dynamic classes.
7472 bool IsContained;
7473 if (const CXXRecordDecl *ContainedRD =
7474 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007475
Nico Weberc44b35e2015-03-21 17:37:46 +00007476 unsigned OperationType = 0;
7477 // "overwritten" if we're warning about the destination for any call
7478 // but memcmp; otherwise a verb appropriate to the call.
7479 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7480 if (BId == Builtin::BImemcpy)
7481 OperationType = 1;
7482 else if(BId == Builtin::BImemmove)
7483 OperationType = 2;
7484 else if (BId == Builtin::BImemcmp)
7485 OperationType = 3;
7486 }
7487
John McCall31168b02011-06-15 23:02:42 +00007488 DiagRuntimeBehavior(
7489 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007490 PDiag(diag::warn_dyn_class_memaccess)
7491 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7492 << FnName << IsContained << ContainedRD << OperationType
7493 << Call->getCallee()->getSourceRange());
7494 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7495 BId != Builtin::BImemset)
7496 DiagRuntimeBehavior(
7497 Dest->getExprLoc(), Dest,
7498 PDiag(diag::warn_arc_object_memaccess)
7499 << ArgIdx << FnName << PointeeTy
7500 << Call->getCallee()->getSourceRange());
7501 else
7502 continue;
7503
7504 DiagRuntimeBehavior(
7505 Dest->getExprLoc(), Dest,
7506 PDiag(diag::note_bad_memaccess_silence)
7507 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7508 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007509 }
7510}
7511
Ted Kremenek6865f772011-08-18 20:55:45 +00007512// A little helper routine: ignore addition and subtraction of integer literals.
7513// This intentionally does not ignore all integer constant expressions because
7514// we don't want to remove sizeof().
7515static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7516 Ex = Ex->IgnoreParenCasts();
7517
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007518 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007519 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7520 if (!BO || !BO->isAdditiveOp())
7521 break;
7522
7523 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7524 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7525
7526 if (isa<IntegerLiteral>(RHS))
7527 Ex = LHS;
7528 else if (isa<IntegerLiteral>(LHS))
7529 Ex = RHS;
7530 else
7531 break;
7532 }
7533
7534 return Ex;
7535}
7536
Anna Zaks13b08572012-08-08 21:42:23 +00007537static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7538 ASTContext &Context) {
7539 // Only handle constant-sized or VLAs, but not flexible members.
7540 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7541 // Only issue the FIXIT for arrays of size > 1.
7542 if (CAT->getSize().getSExtValue() <= 1)
7543 return false;
7544 } else if (!Ty->isVariableArrayType()) {
7545 return false;
7546 }
7547 return true;
7548}
7549
Ted Kremenek6865f772011-08-18 20:55:45 +00007550// Warn if the user has made the 'size' argument to strlcpy or strlcat
7551// be the size of the source, instead of the destination.
7552void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7553 IdentifierInfo *FnName) {
7554
7555 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007556 unsigned NumArgs = Call->getNumArgs();
7557 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007558 return;
7559
7560 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7561 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007562 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007563
7564 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7565 Call->getLocStart(), Call->getRParenLoc()))
7566 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007567
7568 // Look for 'strlcpy(dst, x, sizeof(x))'
7569 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7570 CompareWithSrc = Ex;
7571 else {
7572 // Look for 'strlcpy(dst, x, strlen(x))'
7573 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007574 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7575 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007576 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7577 }
7578 }
7579
7580 if (!CompareWithSrc)
7581 return;
7582
7583 // Determine if the argument to sizeof/strlen is equal to the source
7584 // argument. In principle there's all kinds of things you could do
7585 // here, for instance creating an == expression and evaluating it with
7586 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7587 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7588 if (!SrcArgDRE)
7589 return;
7590
7591 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7592 if (!CompareWithSrcDRE ||
7593 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7594 return;
7595
7596 const Expr *OriginalSizeArg = Call->getArg(2);
7597 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7598 << OriginalSizeArg->getSourceRange() << FnName;
7599
7600 // Output a FIXIT hint if the destination is an array (rather than a
7601 // pointer to an array). This could be enhanced to handle some
7602 // pointers if we know the actual size, like if DstArg is 'array+2'
7603 // we could say 'sizeof(array)-2'.
7604 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007605 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007606 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007607
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007608 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007609 llvm::raw_svector_ostream OS(sizeString);
7610 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007611 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007612 OS << ")";
7613
7614 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7615 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7616 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007617}
7618
Anna Zaks314cd092012-02-01 19:08:57 +00007619/// Check if two expressions refer to the same declaration.
7620static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7621 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7622 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7623 return D1->getDecl() == D2->getDecl();
7624 return false;
7625}
7626
7627static const Expr *getStrlenExprArg(const Expr *E) {
7628 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7629 const FunctionDecl *FD = CE->getDirectCallee();
7630 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007631 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007632 return CE->getArg(0)->IgnoreParenCasts();
7633 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007634 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007635}
7636
7637// Warn on anti-patterns as the 'size' argument to strncat.
7638// The correct size argument should look like following:
7639// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7640void Sema::CheckStrncatArguments(const CallExpr *CE,
7641 IdentifierInfo *FnName) {
7642 // Don't crash if the user has the wrong number of arguments.
7643 if (CE->getNumArgs() < 3)
7644 return;
7645 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7646 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7647 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7648
Nico Weber0e6daef2013-12-26 23:38:39 +00007649 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7650 CE->getRParenLoc()))
7651 return;
7652
Anna Zaks314cd092012-02-01 19:08:57 +00007653 // Identify common expressions, which are wrongly used as the size argument
7654 // to strncat and may lead to buffer overflows.
7655 unsigned PatternType = 0;
7656 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7657 // - sizeof(dst)
7658 if (referToTheSameDecl(SizeOfArg, DstArg))
7659 PatternType = 1;
7660 // - sizeof(src)
7661 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7662 PatternType = 2;
7663 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7664 if (BE->getOpcode() == BO_Sub) {
7665 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7666 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7667 // - sizeof(dst) - strlen(dst)
7668 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7669 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7670 PatternType = 1;
7671 // - sizeof(src) - (anything)
7672 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7673 PatternType = 2;
7674 }
7675 }
7676
7677 if (PatternType == 0)
7678 return;
7679
Anna Zaks5069aa32012-02-03 01:27:37 +00007680 // Generate the diagnostic.
7681 SourceLocation SL = LenArg->getLocStart();
7682 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007683 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007684
7685 // If the function is defined as a builtin macro, do not show macro expansion.
7686 if (SM.isMacroArgExpansion(SL)) {
7687 SL = SM.getSpellingLoc(SL);
7688 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7689 SM.getSpellingLoc(SR.getEnd()));
7690 }
7691
Anna Zaks13b08572012-08-08 21:42:23 +00007692 // Check if the destination is an array (rather than a pointer to an array).
7693 QualType DstTy = DstArg->getType();
7694 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7695 Context);
7696 if (!isKnownSizeArray) {
7697 if (PatternType == 1)
7698 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7699 else
7700 Diag(SL, diag::warn_strncat_src_size) << SR;
7701 return;
7702 }
7703
Anna Zaks314cd092012-02-01 19:08:57 +00007704 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007705 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007706 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007707 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007708
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007709 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007710 llvm::raw_svector_ostream OS(sizeString);
7711 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007712 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007713 OS << ") - ";
7714 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007715 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007716 OS << ") - 1";
7717
Anna Zaks5069aa32012-02-03 01:27:37 +00007718 Diag(SL, diag::note_strncat_wrong_size)
7719 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007720}
7721
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007722//===--- CHECK: Return Address of Stack Variable --------------------------===//
7723
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007724static const Expr *EvalVal(const Expr *E,
7725 SmallVectorImpl<const DeclRefExpr *> &refVars,
7726 const Decl *ParentDecl);
7727static const Expr *EvalAddr(const Expr *E,
7728 SmallVectorImpl<const DeclRefExpr *> &refVars,
7729 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007730
7731/// CheckReturnStackAddr - Check if a return statement returns the address
7732/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007733static void
7734CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7735 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007736 const Expr *stackE = nullptr;
7737 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007738
7739 // Perform checking for returned stack addresses, local blocks,
7740 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007741 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007742 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007743 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007744 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007745 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007746 }
7747
Craig Topperc3ec1492014-05-26 06:22:03 +00007748 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007749 return; // Nothing suspicious was found.
7750
Simon Pilgrim750bde62017-03-31 11:00:53 +00007751 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007752 // of a parameter reference doesn't need a warning.
7753 for (auto *DRE : refVars)
7754 if (isa<ParmVarDecl>(DRE->getDecl()))
7755 return;
7756
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007757 SourceLocation diagLoc;
7758 SourceRange diagRange;
7759 if (refVars.empty()) {
7760 diagLoc = stackE->getLocStart();
7761 diagRange = stackE->getSourceRange();
7762 } else {
7763 // We followed through a reference variable. 'stackE' contains the
7764 // problematic expression but we will warn at the return statement pointing
7765 // at the reference variable. We will later display the "trail" of
7766 // reference variables using notes.
7767 diagLoc = refVars[0]->getLocStart();
7768 diagRange = refVars[0]->getSourceRange();
7769 }
7770
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007771 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7772 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007773 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007774 << DR->getDecl()->getDeclName() << diagRange;
7775 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007776 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007777 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007778 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007779 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007780 // If there is an LValue->RValue conversion, then the value of the
7781 // reference type is used, not the reference.
7782 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7783 if (ICE->getCastKind() == CK_LValueToRValue) {
7784 return;
7785 }
7786 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007787 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7788 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007789 }
7790
7791 // Display the "trail" of reference variables that we followed until we
7792 // found the problematic expression using notes.
7793 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007794 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007795 // If this var binds to another reference var, show the range of the next
7796 // var, otherwise the var binds to the problematic expression, in which case
7797 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007798 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7799 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007800 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7801 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007802 }
7803}
7804
7805/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7806/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007807/// to a location on the stack, a local block, an address of a label, or a
7808/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007809/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007810/// encounter a subexpression that (1) clearly does not lead to one of the
7811/// above problematic expressions (2) is something we cannot determine leads to
7812/// a problematic expression based on such local checking.
7813///
7814/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7815/// the expression that they point to. Such variables are added to the
7816/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007817///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007818/// EvalAddr processes expressions that are pointers that are used as
7819/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007820/// At the base case of the recursion is a check for the above problematic
7821/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007822///
7823/// This implementation handles:
7824///
7825/// * pointer-to-pointer casts
7826/// * implicit conversions from array references to pointers
7827/// * taking the address of fields
7828/// * arbitrary interplay between "&" and "*" operators
7829/// * pointer arithmetic from an address of a stack variable
7830/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007831static const Expr *EvalAddr(const Expr *E,
7832 SmallVectorImpl<const DeclRefExpr *> &refVars,
7833 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007834 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007835 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007836
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007837 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007838 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007839 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007840 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007841 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007842
Peter Collingbourne91147592011-04-15 00:35:48 +00007843 E = E->IgnoreParens();
7844
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007845 // Our "symbolic interpreter" is just a dispatch off the currently
7846 // viewed AST node. We then recursively traverse the AST by calling
7847 // EvalAddr and EvalVal appropriately.
7848 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007849 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007850 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007851
Richard Smith40f08eb2014-01-30 22:05:38 +00007852 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007853 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007854 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007855
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007856 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007857 // If this is a reference variable, follow through to the expression that
7858 // it points to.
7859 if (V->hasLocalStorage() &&
7860 V->getType()->isReferenceType() && V->hasInit()) {
7861 // Add the reference variable to the "trail".
7862 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007863 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007864 }
7865
Craig Topperc3ec1492014-05-26 06:22:03 +00007866 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007867 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007868
Chris Lattner934edb22007-12-28 05:31:15 +00007869 case Stmt::UnaryOperatorClass: {
7870 // The only unary operator that make sense to handle here
7871 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007872 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007873
John McCalle3027922010-08-25 11:45:40 +00007874 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007875 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007876 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007877 }
Mike Stump11289f42009-09-09 15:08:12 +00007878
Chris Lattner934edb22007-12-28 05:31:15 +00007879 case Stmt::BinaryOperatorClass: {
7880 // Handle pointer arithmetic. All other binary operators are not valid
7881 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007882 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007883 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007884
John McCalle3027922010-08-25 11:45:40 +00007885 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007886 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007887
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007888 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007889
7890 // Determine which argument is the real pointer base. It could be
7891 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007892 if (!Base->getType()->isPointerType())
7893 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007894
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007895 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007896 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007897 }
Steve Naroff2752a172008-09-10 19:17:48 +00007898
Chris Lattner934edb22007-12-28 05:31:15 +00007899 // For conditional operators we need to see if either the LHS or RHS are
7900 // valid DeclRefExpr*s. If one of them is valid, we return it.
7901 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007902 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007903
Chris Lattner934edb22007-12-28 05:31:15 +00007904 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007905 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007906 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007907 // In C++, we can have a throw-expression, which has 'void' type.
7908 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007909 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007910 return LHS;
7911 }
Chris Lattner934edb22007-12-28 05:31:15 +00007912
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007913 // In C++, we can have a throw-expression, which has 'void' type.
7914 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007915 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007916
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007917 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007918 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007919
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007920 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007921 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007922 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007923 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007924
7925 case Stmt::AddrLabelExprClass:
7926 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007927
John McCall28fc7092011-11-10 05:35:25 +00007928 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007929 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7930 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007931
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007932 // For casts, we need to handle conversions from arrays to
7933 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007934 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007935 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007936 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007937 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007938 case Stmt::CXXStaticCastExprClass:
7939 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007940 case Stmt::CXXConstCastExprClass:
7941 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007942 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007943 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007944 case CK_LValueToRValue:
7945 case CK_NoOp:
7946 case CK_BaseToDerived:
7947 case CK_DerivedToBase:
7948 case CK_UncheckedDerivedToBase:
7949 case CK_Dynamic:
7950 case CK_CPointerToObjCPointerCast:
7951 case CK_BlockPointerToObjCPointerCast:
7952 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007953 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007954
7955 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007956 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007957
Richard Trieudadefde2014-07-02 04:39:38 +00007958 case CK_BitCast:
7959 if (SubExpr->getType()->isAnyPointerType() ||
7960 SubExpr->getType()->isBlockPointerType() ||
7961 SubExpr->getType()->isObjCQualifiedIdType())
7962 return EvalAddr(SubExpr, refVars, ParentDecl);
7963 else
7964 return nullptr;
7965
Eli Friedman8195ad72012-02-23 23:04:32 +00007966 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007967 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007968 }
Chris Lattner934edb22007-12-28 05:31:15 +00007969 }
Mike Stump11289f42009-09-09 15:08:12 +00007970
Douglas Gregorfe314812011-06-21 17:03:29 +00007971 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007972 if (const Expr *Result =
7973 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7974 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007975 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007976 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007977
Chris Lattner934edb22007-12-28 05:31:15 +00007978 // Everything else: we simply don't reason about them.
7979 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007980 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007981 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007982}
Mike Stump11289f42009-09-09 15:08:12 +00007983
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007984/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7985/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007986static const Expr *EvalVal(const Expr *E,
7987 SmallVectorImpl<const DeclRefExpr *> &refVars,
7988 const Decl *ParentDecl) {
7989 do {
7990 // We should only be called for evaluating non-pointer expressions, or
7991 // expressions with a pointer type that are not used as references but
7992 // instead
7993 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007994
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007995 // Our "symbolic interpreter" is just a dispatch off the currently
7996 // viewed AST node. We then recursively traverse the AST by calling
7997 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007998
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007999 E = E->IgnoreParens();
8000 switch (E->getStmtClass()) {
8001 case Stmt::ImplicitCastExprClass: {
8002 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8003 if (IE->getValueKind() == VK_LValue) {
8004 E = IE->getSubExpr();
8005 continue;
8006 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008007 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008008 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008009
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008010 case Stmt::ExprWithCleanupsClass:
8011 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8012 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008013
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008014 case Stmt::DeclRefExprClass: {
8015 // When we hit a DeclRefExpr we are looking at code that refers to a
8016 // variable's name. If it's not a reference variable we check if it has
8017 // local storage within the function, and if so, return the expression.
8018 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8019
8020 // If we leave the immediate function, the lifetime isn't about to end.
8021 if (DR->refersToEnclosingVariableOrCapture())
8022 return nullptr;
8023
8024 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8025 // Check if it refers to itself, e.g. "int& i = i;".
8026 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008027 return DR;
8028
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008029 if (V->hasLocalStorage()) {
8030 if (!V->getType()->isReferenceType())
8031 return DR;
8032
8033 // Reference variable, follow through to the expression that
8034 // it points to.
8035 if (V->hasInit()) {
8036 // Add the reference variable to the "trail".
8037 refVars.push_back(DR);
8038 return EvalVal(V->getInit(), refVars, V);
8039 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008040 }
8041 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008042
8043 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008044 }
Mike Stump11289f42009-09-09 15:08:12 +00008045
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008046 case Stmt::UnaryOperatorClass: {
8047 // The only unary operator that make sense to handle here
8048 // is Deref. All others don't resolve to a "name." This includes
8049 // handling all sorts of rvalues passed to a unary operator.
8050 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008051
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008052 if (U->getOpcode() == UO_Deref)
8053 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008054
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008055 return nullptr;
8056 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008057
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008058 case Stmt::ArraySubscriptExprClass: {
8059 // Array subscripts are potential references to data on the stack. We
8060 // retrieve the DeclRefExpr* for the array variable if it indeed
8061 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008062 const auto *ASE = cast<ArraySubscriptExpr>(E);
8063 if (ASE->isTypeDependent())
8064 return nullptr;
8065 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008066 }
Mike Stump11289f42009-09-09 15:08:12 +00008067
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008068 case Stmt::OMPArraySectionExprClass: {
8069 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8070 ParentDecl);
8071 }
Mike Stump11289f42009-09-09 15:08:12 +00008072
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008073 case Stmt::ConditionalOperatorClass: {
8074 // For conditional operators we need to see if either the LHS or RHS are
8075 // non-NULL Expr's. If one is non-NULL, we return it.
8076 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008077
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008078 // Handle the GNU extension for missing LHS.
8079 if (const Expr *LHSExpr = C->getLHS()) {
8080 // In C++, we can have a throw-expression, which has 'void' type.
8081 if (!LHSExpr->getType()->isVoidType())
8082 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8083 return LHS;
8084 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008085
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008086 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008087 if (C->getRHS()->getType()->isVoidType())
8088 return nullptr;
8089
8090 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008091 }
8092
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008093 // Accesses to members are potential references to data on the stack.
8094 case Stmt::MemberExprClass: {
8095 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008096
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008097 // Check for indirect access. We only want direct field accesses.
8098 if (M->isArrow())
8099 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008100
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008101 // Check whether the member type is itself a reference, in which case
8102 // we're not going to refer to the member, but to what the member refers
8103 // to.
8104 if (M->getMemberDecl()->getType()->isReferenceType())
8105 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008106
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008107 return EvalVal(M->getBase(), refVars, ParentDecl);
8108 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008109
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008110 case Stmt::MaterializeTemporaryExprClass:
8111 if (const Expr *Result =
8112 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8113 refVars, ParentDecl))
8114 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008115 return E;
8116
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008117 default:
8118 // Check that we don't return or take the address of a reference to a
8119 // temporary. This is only useful in C++.
8120 if (!E->isTypeDependent() && E->isRValue())
8121 return E;
8122
8123 // Everything else: we simply don't reason about them.
8124 return nullptr;
8125 }
8126 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008127}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008128
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008129void
8130Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8131 SourceLocation ReturnLoc,
8132 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008133 const AttrVec *Attrs,
8134 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008135 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8136
8137 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008138 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8139 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008140 CheckNonNullExpr(*this, RetValExp))
8141 Diag(ReturnLoc, diag::warn_null_ret)
8142 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008143
8144 // C++11 [basic.stc.dynamic.allocation]p4:
8145 // If an allocation function declared with a non-throwing
8146 // exception-specification fails to allocate storage, it shall return
8147 // a null pointer. Any other allocation function that fails to allocate
8148 // storage shall indicate failure only by throwing an exception [...]
8149 if (FD) {
8150 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8151 if (Op == OO_New || Op == OO_Array_New) {
8152 const FunctionProtoType *Proto
8153 = FD->getType()->castAs<FunctionProtoType>();
8154 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8155 CheckNonNullExpr(*this, RetValExp))
8156 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8157 << FD << getLangOpts().CPlusPlus11;
8158 }
8159 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008160}
8161
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008162//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8163
8164/// Check for comparisons of floating point operands using != and ==.
8165/// Issue a warning if these are no self-comparisons, as they are not likely
8166/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008167void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008168 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8169 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008170
8171 // Special case: check for x == x (which is OK).
8172 // Do not emit warnings for such cases.
8173 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8174 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8175 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008176 return;
Mike Stump11289f42009-09-09 15:08:12 +00008177
Ted Kremenekeda40e22007-11-29 00:59:04 +00008178 // Special case: check for comparisons against literals that can be exactly
8179 // represented by APFloat. In such cases, do not emit a warning. This
8180 // is a heuristic: often comparison against such literals are used to
8181 // detect if a value in a variable has not changed. This clearly can
8182 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008183 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8184 if (FLL->isExact())
8185 return;
8186 } else
8187 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8188 if (FLR->isExact())
8189 return;
Mike Stump11289f42009-09-09 15:08:12 +00008190
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008191 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008192 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008193 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008194 return;
Mike Stump11289f42009-09-09 15:08:12 +00008195
David Blaikie1f4ff152012-07-16 20:47:22 +00008196 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008197 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008198 return;
Mike Stump11289f42009-09-09 15:08:12 +00008199
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008200 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008201 Diag(Loc, diag::warn_floatingpoint_eq)
8202 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008203}
John McCallca01b222010-01-04 23:21:16 +00008204
John McCall70aa5392010-01-06 05:24:50 +00008205//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8206//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008207
John McCall70aa5392010-01-06 05:24:50 +00008208namespace {
John McCallca01b222010-01-04 23:21:16 +00008209
John McCall70aa5392010-01-06 05:24:50 +00008210/// Structure recording the 'active' range of an integer-valued
8211/// expression.
8212struct IntRange {
8213 /// The number of bits active in the int.
8214 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008215
John McCall70aa5392010-01-06 05:24:50 +00008216 /// True if the int is known not to have negative values.
8217 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008218
John McCall70aa5392010-01-06 05:24:50 +00008219 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008220 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008221
John McCall817d4af2010-11-10 23:38:19 +00008222 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008223 static IntRange forBoolType() {
8224 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008225 }
8226
John McCall817d4af2010-11-10 23:38:19 +00008227 /// Returns the range of an opaque value of the given integral type.
8228 static IntRange forValueOfType(ASTContext &C, QualType T) {
8229 return forValueOfCanonicalType(C,
8230 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008231 }
8232
John McCall817d4af2010-11-10 23:38:19 +00008233 /// Returns the range of an opaque value of a canonical integral type.
8234 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008235 assert(T->isCanonicalUnqualified());
8236
8237 if (const VectorType *VT = dyn_cast<VectorType>(T))
8238 T = VT->getElementType().getTypePtr();
8239 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8240 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008241 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8242 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008243
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008244 if (!C.getLangOpts().CPlusPlus) {
8245 // For enum types in C code, use the underlying datatype.
8246 if (const EnumType *ET = dyn_cast<EnumType>(T))
8247 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8248 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8249 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008250 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008251 // In C++11, enums can have a fixed underlying type. Use this type to
8252 // compute the range.
8253 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008254 return IntRange(C.getIntWidth(QualType(T, 0)),
8255 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008256 }
John McCall18a2c2c2010-11-09 22:22:12 +00008257
David Majnemer6a426652013-06-07 22:07:20 +00008258 unsigned NumPositive = Enum->getNumPositiveBits();
8259 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008260
David Majnemer6a426652013-06-07 22:07:20 +00008261 if (NumNegative == 0)
8262 return IntRange(NumPositive, true/*NonNegative*/);
8263 else
8264 return IntRange(std::max(NumPositive + 1, NumNegative),
8265 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008266 }
John McCall70aa5392010-01-06 05:24:50 +00008267
8268 const BuiltinType *BT = cast<BuiltinType>(T);
8269 assert(BT->isInteger());
8270
8271 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8272 }
8273
John McCall817d4af2010-11-10 23:38:19 +00008274 /// Returns the "target" range of a canonical integral type, i.e.
8275 /// the range of values expressible in the type.
8276 ///
8277 /// This matches forValueOfCanonicalType except that enums have the
8278 /// full range of their type, not the range of their enumerators.
8279 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8280 assert(T->isCanonicalUnqualified());
8281
8282 if (const VectorType *VT = dyn_cast<VectorType>(T))
8283 T = VT->getElementType().getTypePtr();
8284 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8285 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008286 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8287 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008288 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008289 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008290
8291 const BuiltinType *BT = cast<BuiltinType>(T);
8292 assert(BT->isInteger());
8293
8294 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8295 }
8296
8297 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008298 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008299 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008300 L.NonNegative && R.NonNegative);
8301 }
8302
John McCall817d4af2010-11-10 23:38:19 +00008303 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008304 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008305 return IntRange(std::min(L.Width, R.Width),
8306 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008307 }
8308};
8309
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008310} // namespace
8311
8312static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8313 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008314 if (value.isSigned() && value.isNegative())
8315 return IntRange(value.getMinSignedBits(), false);
8316
8317 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008318 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008319
8320 // isNonNegative() just checks the sign bit without considering
8321 // signedness.
8322 return IntRange(value.getActiveBits(), true);
8323}
8324
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008325static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8326 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008327 if (result.isInt())
8328 return GetValueRange(C, result.getInt(), MaxWidth);
8329
8330 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008331 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8332 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8333 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8334 R = IntRange::join(R, El);
8335 }
John McCall70aa5392010-01-06 05:24:50 +00008336 return R;
8337 }
8338
8339 if (result.isComplexInt()) {
8340 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8341 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8342 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008343 }
8344
8345 // This can happen with lossless casts to intptr_t of "based" lvalues.
8346 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008347 // FIXME: The only reason we need to pass the type in here is to get
8348 // the sign right on this one case. It would be nice if APValue
8349 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008350 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008351 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008352}
John McCall70aa5392010-01-06 05:24:50 +00008353
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008354static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008355 QualType Ty = E->getType();
8356 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8357 Ty = AtomicRHS->getValueType();
8358 return Ty;
8359}
8360
John McCall70aa5392010-01-06 05:24:50 +00008361/// Pseudo-evaluate the given integer expression, estimating the
8362/// range of values it might take.
8363///
8364/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008365static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008366 E = E->IgnoreParens();
8367
8368 // Try a full evaluation first.
8369 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008370 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008371 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008372
8373 // I think we only want to look through implicit casts here; if the
8374 // user has an explicit widening cast, we should treat the value as
8375 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008376 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008377 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008378 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8379
Eli Friedmane6d33952013-07-08 20:20:06 +00008380 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008381
George Burgess IVdf1ed002016-01-13 01:52:39 +00008382 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8383 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008384
John McCall70aa5392010-01-06 05:24:50 +00008385 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008386 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008387 return OutputTypeRange;
8388
8389 IntRange SubRange
8390 = GetExprRange(C, CE->getSubExpr(),
8391 std::min(MaxWidth, OutputTypeRange.Width));
8392
8393 // Bail out if the subexpr's range is as wide as the cast type.
8394 if (SubRange.Width >= OutputTypeRange.Width)
8395 return OutputTypeRange;
8396
8397 // Otherwise, we take the smaller width, and we're non-negative if
8398 // either the output type or the subexpr is.
8399 return IntRange(SubRange.Width,
8400 SubRange.NonNegative || OutputTypeRange.NonNegative);
8401 }
8402
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008403 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008404 // If we can fold the condition, just take that operand.
8405 bool CondResult;
8406 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8407 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8408 : CO->getFalseExpr(),
8409 MaxWidth);
8410
8411 // Otherwise, conservatively merge.
8412 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8413 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8414 return IntRange::join(L, R);
8415 }
8416
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008417 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008418 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008419 case BO_Cmp:
8420 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008421
8422 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008423 case BO_LAnd:
8424 case BO_LOr:
8425 case BO_LT:
8426 case BO_GT:
8427 case BO_LE:
8428 case BO_GE:
8429 case BO_EQ:
8430 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008431 return IntRange::forBoolType();
8432
John McCallc3688382011-07-13 06:35:24 +00008433 // The type of the assignments is the type of the LHS, so the RHS
8434 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008435 case BO_MulAssign:
8436 case BO_DivAssign:
8437 case BO_RemAssign:
8438 case BO_AddAssign:
8439 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008440 case BO_XorAssign:
8441 case BO_OrAssign:
8442 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008443 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008444
John McCallc3688382011-07-13 06:35:24 +00008445 // Simple assignments just pass through the RHS, which will have
8446 // been coerced to the LHS type.
8447 case BO_Assign:
8448 // TODO: bitfields?
8449 return GetExprRange(C, BO->getRHS(), MaxWidth);
8450
John McCall70aa5392010-01-06 05:24:50 +00008451 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008452 case BO_PtrMemD:
8453 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008454 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008455
John McCall2ce81ad2010-01-06 22:07:33 +00008456 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008457 case BO_And:
8458 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008459 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8460 GetExprRange(C, BO->getRHS(), MaxWidth));
8461
John McCall70aa5392010-01-06 05:24:50 +00008462 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008463 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008464 // ...except that we want to treat '1 << (blah)' as logically
8465 // positive. It's an important idiom.
8466 if (IntegerLiteral *I
8467 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8468 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008469 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008470 return IntRange(R.Width, /*NonNegative*/ true);
8471 }
8472 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008473 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008474
John McCalle3027922010-08-25 11:45:40 +00008475 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008476 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008477
John McCall2ce81ad2010-01-06 22:07:33 +00008478 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008479 case BO_Shr:
8480 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008481 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8482
8483 // If the shift amount is a positive constant, drop the width by
8484 // that much.
8485 llvm::APSInt shift;
8486 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8487 shift.isNonNegative()) {
8488 unsigned zext = shift.getZExtValue();
8489 if (zext >= L.Width)
8490 L.Width = (L.NonNegative ? 0 : 1);
8491 else
8492 L.Width -= zext;
8493 }
8494
8495 return L;
8496 }
8497
8498 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008499 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008500 return GetExprRange(C, BO->getRHS(), MaxWidth);
8501
John McCall2ce81ad2010-01-06 22:07:33 +00008502 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008503 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008504 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008505 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008506 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008507
John McCall51431812011-07-14 22:39:48 +00008508 // The width of a division result is mostly determined by the size
8509 // of the LHS.
8510 case BO_Div: {
8511 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008512 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008513 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8514
8515 // If the divisor is constant, use that.
8516 llvm::APSInt divisor;
8517 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8518 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8519 if (log2 >= L.Width)
8520 L.Width = (L.NonNegative ? 0 : 1);
8521 else
8522 L.Width = std::min(L.Width - log2, MaxWidth);
8523 return L;
8524 }
8525
8526 // Otherwise, just use the LHS's width.
8527 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8528 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8529 }
8530
8531 // The result of a remainder can't be larger than the result of
8532 // either side.
8533 case BO_Rem: {
8534 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008535 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008536 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8537 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8538
8539 IntRange meet = IntRange::meet(L, R);
8540 meet.Width = std::min(meet.Width, MaxWidth);
8541 return meet;
8542 }
8543
8544 // The default behavior is okay for these.
8545 case BO_Mul:
8546 case BO_Add:
8547 case BO_Xor:
8548 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008549 break;
8550 }
8551
John McCall51431812011-07-14 22:39:48 +00008552 // The default case is to treat the operation as if it were closed
8553 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008554 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8555 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8556 return IntRange::join(L, R);
8557 }
8558
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008559 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008560 switch (UO->getOpcode()) {
8561 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008562 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008563 return IntRange::forBoolType();
8564
8565 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008566 case UO_Deref:
8567 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008568 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008569
8570 default:
8571 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8572 }
8573 }
8574
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008575 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008576 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8577
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008578 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008579 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008580 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008581
Eli Friedmane6d33952013-07-08 20:20:06 +00008582 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008583}
John McCall263a48b2010-01-04 23:31:57 +00008584
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008585static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008586 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008587}
8588
John McCall263a48b2010-01-04 23:31:57 +00008589/// Checks whether the given value, which currently has the given
8590/// source semantics, has the same value when coerced through the
8591/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008592static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8593 const llvm::fltSemantics &Src,
8594 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008595 llvm::APFloat truncated = value;
8596
8597 bool ignored;
8598 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8599 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8600
8601 return truncated.bitwiseIsEqual(value);
8602}
8603
8604/// Checks whether the given value, which currently has the given
8605/// source semantics, has the same value when coerced through the
8606/// target semantics.
8607///
8608/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008609static bool IsSameFloatAfterCast(const APValue &value,
8610 const llvm::fltSemantics &Src,
8611 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008612 if (value.isFloat())
8613 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8614
8615 if (value.isVector()) {
8616 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8617 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8618 return false;
8619 return true;
8620 }
8621
8622 assert(value.isComplexFloat());
8623 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8624 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8625}
8626
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008627static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008628
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008629static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008630 // Suppress cases where we are comparing against an enum constant.
8631 if (const DeclRefExpr *DR =
8632 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8633 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008634 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008635
8636 // Suppress cases where the '0' value is expanded from a macro.
8637 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008638 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008639
Roman Lebedev6de129e2017-10-15 20:13:17 +00008640 return false;
8641}
8642
Richard Smith692f66ab2017-12-06 19:23:19 +00008643static bool isKnownToHaveUnsignedValue(Expr *E) {
8644 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00008645 (!E->getType()->isSignedIntegerType() ||
8646 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8647}
8648
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008649namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00008650/// The promoted range of values of a type. In general this has the
8651/// following structure:
8652///
8653/// |-----------| . . . |-----------|
8654/// ^ ^ ^ ^
8655/// Min HoleMin HoleMax Max
8656///
8657/// ... where there is only a hole if a signed type is promoted to unsigned
8658/// (in which case Min and Max are the smallest and largest representable
8659/// values).
8660struct PromotedRange {
8661 // Min, or HoleMax if there is a hole.
8662 llvm::APSInt PromotedMin;
8663 // Max, or HoleMin if there is a hole.
8664 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008665
Richard Smitha5370fb2017-12-08 22:57:11 +00008666 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8667 if (R.Width == 0)
8668 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8669 else if (R.Width >= BitWidth && !Unsigned) {
8670 // Promotion made the type *narrower*. This happens when promoting
8671 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8672 // Treat all values of 'signed int' as being in range for now.
8673 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8674 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8675 } else {
8676 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8677 .extOrTrunc(BitWidth);
8678 PromotedMin.setIsUnsigned(Unsigned);
8679
8680 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8681 .extOrTrunc(BitWidth);
8682 PromotedMax.setIsUnsigned(Unsigned);
8683 }
8684 }
8685
8686 // Determine whether this range is contiguous (has no hole).
8687 bool isContiguous() const { return PromotedMin <= PromotedMax; }
8688
8689 // Where a constant value is within the range.
8690 enum ComparisonResult {
8691 LT = 0x1,
8692 LE = 0x2,
8693 GT = 0x4,
8694 GE = 0x8,
8695 EQ = 0x10,
8696 NE = 0x20,
8697 InRangeFlag = 0x40,
8698
8699 Less = LE | LT | NE,
8700 Min = LE | InRangeFlag,
8701 InRange = InRangeFlag,
8702 Max = GE | InRangeFlag,
8703 Greater = GE | GT | NE,
8704
8705 OnlyValue = LE | GE | EQ | InRangeFlag,
8706 InHole = NE
8707 };
8708
8709 ComparisonResult compare(const llvm::APSInt &Value) const {
8710 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8711 Value.isUnsigned() == PromotedMin.isUnsigned());
8712 if (!isContiguous()) {
8713 assert(Value.isUnsigned() && "discontiguous range for signed compare");
8714 if (Value.isMinValue()) return Min;
8715 if (Value.isMaxValue()) return Max;
8716 if (Value >= PromotedMin) return InRange;
8717 if (Value <= PromotedMax) return InRange;
8718 return InHole;
8719 }
8720
8721 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8722 case -1: return Less;
8723 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8724 case 1:
8725 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8726 case -1: return InRange;
8727 case 0: return Max;
8728 case 1: return Greater;
8729 }
8730 }
8731
8732 llvm_unreachable("impossible compare result");
8733 }
8734
Richard Smithc70f1d62017-12-14 15:16:18 +00008735 static llvm::Optional<StringRef>
8736 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8737 if (Op == BO_Cmp) {
8738 ComparisonResult LTFlag = LT, GTFlag = GT;
8739 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8740
8741 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8742 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8743 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8744 return llvm::None;
8745 }
8746
Richard Smitha5370fb2017-12-08 22:57:11 +00008747 ComparisonResult TrueFlag, FalseFlag;
8748 if (Op == BO_EQ) {
8749 TrueFlag = EQ;
8750 FalseFlag = NE;
8751 } else if (Op == BO_NE) {
8752 TrueFlag = NE;
8753 FalseFlag = EQ;
8754 } else {
8755 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8756 TrueFlag = LT;
8757 FalseFlag = GE;
8758 } else {
8759 TrueFlag = GT;
8760 FalseFlag = LE;
8761 }
8762 if (Op == BO_GE || Op == BO_LE)
8763 std::swap(TrueFlag, FalseFlag);
8764 }
8765 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008766 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00008767 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008768 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00008769 return llvm::None;
8770 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00008771};
John McCallcc7e5bf2010-05-06 08:58:33 +00008772}
8773
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008774static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008775 // Strip off implicit integral promotions.
8776 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008777 if (ICE->getCastKind() != CK_IntegralCast &&
8778 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008779 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008780 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008781 }
8782
8783 return E->getType()->isEnumeralType();
8784}
8785
Richard Smith692f66ab2017-12-06 19:23:19 +00008786static int classifyConstantValue(Expr *Constant) {
8787 // The values of this enumeration are used in the diagnostics
8788 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8789 enum ConstantValueKind {
8790 Miscellaneous = 0,
8791 LiteralTrue,
8792 LiteralFalse
8793 };
8794 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8795 return BL->getValue() ? ConstantValueKind::LiteralTrue
8796 : ConstantValueKind::LiteralFalse;
8797 return ConstantValueKind::Miscellaneous;
8798}
8799
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008800static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8801 Expr *Constant, Expr *Other,
8802 const llvm::APSInt &Value,
8803 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008804 if (S.inTemplateInstantiation())
8805 return false;
8806
Richard Smitha5370fb2017-12-08 22:57:11 +00008807 Expr *OriginalOther = Other;
8808
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008809 Constant = Constant->IgnoreParenImpCasts();
8810 Other = Other->IgnoreParenImpCasts();
8811
Richard Smitha5370fb2017-12-08 22:57:11 +00008812 // Suppress warnings on tautological comparisons between values of the same
8813 // enumeration type. There are only two ways we could warn on this:
8814 // - If the constant is outside the range of representable values of
8815 // the enumeration. In such a case, we should warn about the cast
8816 // to enumeration type, not about the comparison.
8817 // - If the constant is the maximum / minimum in-range value. For an
8818 // enumeratin type, such comparisons can be meaningful and useful.
8819 if (Constant->getType()->isEnumeralType() &&
8820 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8821 return false;
8822
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008823 // TODO: Investigate using GetExprRange() to get tighter bounds
8824 // on the bit ranges.
8825 QualType OtherT = Other->getType();
8826 if (const auto *AT = OtherT->getAs<AtomicType>())
8827 OtherT = AT->getValueType();
8828 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8829
8830 // Whether we're treating Other as being a bool because of the form of
8831 // expression despite it having another type (typically 'int' in C).
8832 bool OtherIsBooleanDespiteType =
8833 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8834 if (OtherIsBooleanDespiteType)
8835 OtherRange = IntRange::forBoolType();
8836
Richard Smitha5370fb2017-12-08 22:57:11 +00008837 // Determine the promoted range of the other type and see if a comparison of
8838 // the constant against that range is tautological.
8839 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8840 Value.isUnsigned());
8841 auto Cmp = OtherPromotedRange.compare(Value);
8842 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8843 if (!Result)
8844 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00008845
Richard Smitha5370fb2017-12-08 22:57:11 +00008846 // Suppress the diagnostic for an in-range comparison if the constant comes
8847 // from a macro or enumerator. We don't want to diagnose
8848 //
8849 // some_long_value <= INT_MAX
8850 //
8851 // when sizeof(int) == sizeof(long).
8852 bool InRange = Cmp & PromotedRange::InRangeFlag;
8853 if (InRange && IsEnumConstOrFromMacro(S, Constant))
8854 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008855
8856 // If this is a comparison to an enum constant, include that
8857 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008858 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008859 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8860 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8861
Richard Smitha5370fb2017-12-08 22:57:11 +00008862 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008863 SmallString<64> PrettySourceValue;
8864 llvm::raw_svector_ostream OS(PrettySourceValue);
8865 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008866 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008867 else
8868 OS << Value;
8869
Richard Smitha5370fb2017-12-08 22:57:11 +00008870 // FIXME: We use a somewhat different formatting for the in-range cases and
8871 // cases involving boolean values for historical reasons. We should pick a
8872 // consistent way of presenting these diagnostics.
8873 if (!InRange || Other->isKnownToHaveBooleanValue()) {
8874 S.DiagRuntimeBehavior(
8875 E->getOperatorLoc(), E,
8876 S.PDiag(!InRange ? diag::warn_out_of_range_compare
8877 : diag::warn_tautological_bool_compare)
8878 << OS.str() << classifyConstantValue(Constant)
8879 << OtherT << OtherIsBooleanDespiteType << *Result
8880 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8881 } else {
8882 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8883 ? (HasEnumType(OriginalOther)
8884 ? diag::warn_unsigned_enum_always_true_comparison
8885 : diag::warn_unsigned_always_true_comparison)
8886 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00008887
Richard Smitha5370fb2017-12-08 22:57:11 +00008888 S.Diag(E->getOperatorLoc(), Diag)
8889 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8890 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8891 }
8892
8893 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008894}
8895
John McCallcc7e5bf2010-05-06 08:58:33 +00008896/// Analyze the operands of the given comparison. Implements the
8897/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008898static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008899 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8900 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008901}
John McCall263a48b2010-01-04 23:31:57 +00008902
John McCallca01b222010-01-04 23:21:16 +00008903/// \brief Implements -Wsign-compare.
8904///
Richard Trieu82402a02011-09-15 21:56:47 +00008905/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008906static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008907 // The type the comparison is being performed in.
8908 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008909
8910 // Only analyze comparison operators where both sides have been converted to
8911 // the same type.
8912 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8913 return AnalyzeImpConvsInComparison(S, E);
8914
8915 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008916 if (E->isValueDependent())
8917 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008918
Roman Lebedev6de129e2017-10-15 20:13:17 +00008919 Expr *LHS = E->getLHS();
8920 Expr *RHS = E->getRHS();
8921
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008922 if (T->isIntegralType(S.Context)) {
8923 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008924 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008925
Roman Lebedev6de129e2017-10-15 20:13:17 +00008926 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8927 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008928
Roman Lebedev6de129e2017-10-15 20:13:17 +00008929 // We don't care about expressions whose result is a constant.
8930 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8931 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00008932
Roman Lebedev6de129e2017-10-15 20:13:17 +00008933 // We only care about expressions where just one side is literal
8934 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8935 // Is the constant on the RHS or LHS?
8936 const bool RhsConstant = IsRHSIntegralLiteral;
8937 Expr *Const = RhsConstant ? RHS : LHS;
8938 Expr *Other = RhsConstant ? LHS : RHS;
8939 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8940
8941 // Check whether an integer constant comparison results in a value
8942 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00008943 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8944 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008945 }
8946 }
8947
8948 if (!T->hasUnsignedIntegerRepresentation()) {
8949 // We don't do anything special if this isn't an unsigned integral
8950 // comparison: we're only interested in integral comparisons, and
8951 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00008952 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008953 }
8954
8955 LHS = LHS->IgnoreParenImpCasts();
8956 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008957
John McCallcc7e5bf2010-05-06 08:58:33 +00008958 // Check to see if one of the (unmodified) operands is of different
8959 // signedness.
8960 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008961 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8962 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008963 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008964 signedOperand = LHS;
8965 unsignedOperand = RHS;
8966 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8967 signedOperand = RHS;
8968 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008969 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008970 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008971 }
8972
John McCallcc7e5bf2010-05-06 08:58:33 +00008973 // Otherwise, calculate the effective range of the signed operand.
8974 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008975
John McCallcc7e5bf2010-05-06 08:58:33 +00008976 // Go ahead and analyze implicit conversions in the operands. Note
8977 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008978 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8979 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008980
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008981 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00008982 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008983 return;
John McCallca01b222010-01-04 23:21:16 +00008984
8985 // For (in)equality comparisons, if the unsigned operand is a
8986 // constant which cannot collide with a overflowed signed operand,
8987 // then reinterpreting the signed operand as unsigned will not
8988 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008989 if (E->isEqualityOp()) {
8990 unsigned comparisonWidth = S.Context.getIntWidth(T);
8991 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008992
John McCallcc7e5bf2010-05-06 08:58:33 +00008993 // We should never be unable to prove that the unsigned operand is
8994 // non-negative.
8995 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8996
8997 if (unsignedRange.Width < comparisonWidth)
8998 return;
8999 }
9000
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009001 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9002 S.PDiag(diag::warn_mixed_sign_comparison)
9003 << LHS->getType() << RHS->getType()
9004 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009005}
9006
John McCall1f425642010-11-11 03:21:53 +00009007/// Analyzes an attempt to assign the given value to a bitfield.
9008///
9009/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009010static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9011 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009012 assert(Bitfield->isBitField());
9013 if (Bitfield->isInvalidDecl())
9014 return false;
9015
John McCalldeebbcf2010-11-11 05:33:51 +00009016 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009017 QualType BitfieldType = Bitfield->getType();
9018 if (BitfieldType->isBooleanType())
9019 return false;
9020
9021 if (BitfieldType->isEnumeralType()) {
9022 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9023 // If the underlying enum type was not explicitly specified as an unsigned
9024 // type and the enum contain only positive values, MSVC++ will cause an
9025 // inconsistency by storing this as a signed type.
9026 if (S.getLangOpts().CPlusPlus11 &&
9027 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9028 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9029 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9030 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9031 << BitfieldEnumDecl->getNameAsString();
9032 }
9033 }
9034
John McCalldeebbcf2010-11-11 05:33:51 +00009035 if (Bitfield->getType()->isBooleanType())
9036 return false;
9037
Douglas Gregor789adec2011-02-04 13:09:01 +00009038 // Ignore value- or type-dependent expressions.
9039 if (Bitfield->getBitWidth()->isValueDependent() ||
9040 Bitfield->getBitWidth()->isTypeDependent() ||
9041 Init->isValueDependent() ||
9042 Init->isTypeDependent())
9043 return false;
9044
John McCall1f425642010-11-11 03:21:53 +00009045 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009046 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009047
Richard Smith5fab0c92011-12-28 19:48:30 +00009048 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009049 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9050 Expr::SE_AllowSideEffects)) {
9051 // The RHS is not constant. If the RHS has an enum type, make sure the
9052 // bitfield is wide enough to hold all the values of the enum without
9053 // truncation.
9054 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9055 EnumDecl *ED = EnumTy->getDecl();
9056 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9057
9058 // Enum types are implicitly signed on Windows, so check if there are any
9059 // negative enumerators to see if the enum was intended to be signed or
9060 // not.
9061 bool SignedEnum = ED->getNumNegativeBits() > 0;
9062
9063 // Check for surprising sign changes when assigning enum values to a
9064 // bitfield of different signedness. If the bitfield is signed and we
9065 // have exactly the right number of bits to store this unsigned enum,
9066 // suggest changing the enum to an unsigned type. This typically happens
9067 // on Windows where unfixed enums always use an underlying type of 'int'.
9068 unsigned DiagID = 0;
9069 if (SignedEnum && !SignedBitfield) {
9070 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9071 } else if (SignedBitfield && !SignedEnum &&
9072 ED->getNumPositiveBits() == FieldWidth) {
9073 DiagID = diag::warn_signed_bitfield_enum_conversion;
9074 }
9075
9076 if (DiagID) {
9077 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9078 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9079 SourceRange TypeRange =
9080 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9081 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9082 << SignedEnum << TypeRange;
9083 }
9084
9085 // Compute the required bitwidth. If the enum has negative values, we need
9086 // one more bit than the normal number of positive bits to represent the
9087 // sign bit.
9088 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9089 ED->getNumNegativeBits())
9090 : ED->getNumPositiveBits();
9091
9092 // Check the bitwidth.
9093 if (BitsNeeded > FieldWidth) {
9094 Expr *WidthExpr = Bitfield->getBitWidth();
9095 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9096 << Bitfield << ED;
9097 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9098 << BitsNeeded << ED << WidthExpr->getSourceRange();
9099 }
9100 }
9101
John McCall1f425642010-11-11 03:21:53 +00009102 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009103 }
John McCall1f425642010-11-11 03:21:53 +00009104
John McCall1f425642010-11-11 03:21:53 +00009105 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009106
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009107 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009108 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009109 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9110 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009111
John McCall1f425642010-11-11 03:21:53 +00009112 if (OriginalWidth <= FieldWidth)
9113 return false;
9114
Eli Friedmanc267a322012-01-26 23:11:39 +00009115 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009116 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009117 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009118
Eli Friedmanc267a322012-01-26 23:11:39 +00009119 // Check whether the stored value is equal to the original value.
9120 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009121 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009122 return false;
9123
Eli Friedmanc267a322012-01-26 23:11:39 +00009124 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009125 // therefore don't strictly fit into a signed bitfield of width 1.
9126 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009127 return false;
9128
John McCall1f425642010-11-11 03:21:53 +00009129 std::string PrettyValue = Value.toString(10);
9130 std::string PrettyTrunc = TruncatedValue.toString(10);
9131
9132 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9133 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9134 << Init->getSourceRange();
9135
9136 return true;
9137}
9138
John McCalld2a53122010-11-09 23:24:47 +00009139/// Analyze the given simple or compound assignment for warning-worthy
9140/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009141static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009142 // Just recurse on the LHS.
9143 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9144
9145 // We want to recurse on the RHS as normal unless we're assigning to
9146 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009147 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009148 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009149 E->getOperatorLoc())) {
9150 // Recurse, ignoring any implicit conversions on the RHS.
9151 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9152 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009153 }
9154 }
9155
9156 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9157}
9158
John McCall263a48b2010-01-04 23:31:57 +00009159/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009160static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9161 SourceLocation CContext, unsigned diag,
9162 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009163 if (pruneControlFlow) {
9164 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9165 S.PDiag(diag)
9166 << SourceType << T << E->getSourceRange()
9167 << SourceRange(CContext));
9168 return;
9169 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009170 S.Diag(E->getExprLoc(), diag)
9171 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9172}
9173
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009174/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009175static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9176 SourceLocation CContext,
9177 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009178 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009179}
9180
Richard Trieube234c32016-04-21 21:04:55 +00009181
9182/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009183static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9184 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009185 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009186 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009187
9188 Expr *InnerE = E->IgnoreParenImpCasts();
9189 // We also want to warn on, e.g., "int i = -1.234"
9190 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9191 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9192 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9193
9194 const bool IsLiteral =
9195 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9196
9197 llvm::APFloat Value(0.0);
9198 bool IsConstant =
9199 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9200 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009201 return DiagnoseImpCast(S, E, T, CContext,
9202 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009203 }
9204
Chandler Carruth016ef402011-04-10 08:36:24 +00009205 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009206
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009207 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9208 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009209 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9210 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009211 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009212 if (IsLiteral) return;
9213 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9214 PruneWarnings);
9215 }
9216
9217 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009218 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009219 // Warn on floating point literal to integer.
9220 DiagID = diag::warn_impcast_literal_float_to_integer;
9221 } else if (IntegerValue == 0) {
9222 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9223 return DiagnoseImpCast(S, E, T, CContext,
9224 diag::warn_impcast_float_integer, PruneWarnings);
9225 }
9226 // Warn on non-zero to zero conversion.
9227 DiagID = diag::warn_impcast_float_to_integer_zero;
9228 } else {
9229 if (IntegerValue.isUnsigned()) {
9230 if (!IntegerValue.isMaxValue()) {
9231 return DiagnoseImpCast(S, E, T, CContext,
9232 diag::warn_impcast_float_integer, PruneWarnings);
9233 }
9234 } else { // IntegerValue.isSigned()
9235 if (!IntegerValue.isMaxSignedValue() &&
9236 !IntegerValue.isMinSignedValue()) {
9237 return DiagnoseImpCast(S, E, T, CContext,
9238 diag::warn_impcast_float_integer, PruneWarnings);
9239 }
9240 }
9241 // Warn on evaluatable floating point expression to integer conversion.
9242 DiagID = diag::warn_impcast_float_to_integer;
9243 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009244
Eli Friedman07185912013-08-29 23:44:43 +00009245 // FIXME: Force the precision of the source value down so we don't print
9246 // digits which are usually useless (we don't really care here if we
9247 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9248 // would automatically print the shortest representation, but it's a bit
9249 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009250 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009251 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9252 precision = (precision * 59 + 195) / 196;
9253 Value.toString(PrettySourceValue, precision);
9254
David Blaikie9b88cc02012-05-15 17:18:27 +00009255 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009256 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009257 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009258 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009259 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009260
Richard Trieube234c32016-04-21 21:04:55 +00009261 if (PruneWarnings) {
9262 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9263 S.PDiag(DiagID)
9264 << E->getType() << T.getUnqualifiedType()
9265 << PrettySourceValue << PrettyTargetValue
9266 << E->getSourceRange() << SourceRange(CContext));
9267 } else {
9268 S.Diag(E->getExprLoc(), DiagID)
9269 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9270 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9271 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009272}
9273
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009274static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9275 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009276 if (!Range.Width) return "0";
9277
9278 llvm::APSInt ValueInRange = Value;
9279 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009280 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009281 return ValueInRange.toString(10);
9282}
9283
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009284static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009285 if (!isa<ImplicitCastExpr>(Ex))
9286 return false;
9287
9288 Expr *InnerE = Ex->IgnoreParenImpCasts();
9289 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9290 const Type *Source =
9291 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9292 if (Target->isDependentType())
9293 return false;
9294
9295 const BuiltinType *FloatCandidateBT =
9296 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9297 const Type *BoolCandidateType = ToBool ? Target : Source;
9298
9299 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9300 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9301}
9302
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009303static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9304 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009305 unsigned NumArgs = TheCall->getNumArgs();
9306 for (unsigned i = 0; i < NumArgs; ++i) {
9307 Expr *CurrA = TheCall->getArg(i);
9308 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9309 continue;
9310
9311 bool IsSwapped = ((i > 0) &&
9312 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9313 IsSwapped |= ((i < (NumArgs - 1)) &&
9314 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9315 if (IsSwapped) {
9316 // Warn on this floating-point to bool conversion.
9317 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9318 CurrA->getType(), CC,
9319 diag::warn_impcast_floating_point_to_bool);
9320 }
9321 }
9322}
9323
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009324static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9325 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009326 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9327 E->getExprLoc()))
9328 return;
9329
Richard Trieu09d6b802016-01-08 23:35:06 +00009330 // Don't warn on functions which have return type nullptr_t.
9331 if (isa<CallExpr>(E))
9332 return;
9333
Richard Trieu5b993502014-10-15 03:42:06 +00009334 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9335 const Expr::NullPointerConstantKind NullKind =
9336 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9337 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9338 return;
9339
9340 // Return if target type is a safe conversion.
9341 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9342 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9343 return;
9344
9345 SourceLocation Loc = E->getSourceRange().getBegin();
9346
Richard Trieu0a5e1662016-02-13 00:58:53 +00009347 // Venture through the macro stacks to get to the source of macro arguments.
9348 // The new location is a better location than the complete location that was
9349 // passed in.
9350 while (S.SourceMgr.isMacroArgExpansion(Loc))
9351 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9352
9353 while (S.SourceMgr.isMacroArgExpansion(CC))
9354 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9355
Richard Trieu5b993502014-10-15 03:42:06 +00009356 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009357 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9358 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9359 Loc, S.SourceMgr, S.getLangOpts());
9360 if (MacroName == "NULL")
9361 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009362 }
9363
9364 // Only warn if the null and context location are in the same macro expansion.
9365 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9366 return;
9367
9368 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009369 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009370 << FixItHint::CreateReplacement(Loc,
9371 S.getFixItZeroLiteralForType(T, Loc));
9372}
9373
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009374static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9375 ObjCArrayLiteral *ArrayLiteral);
9376
9377static void
9378checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9379 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009380
9381/// Check a single element within a collection literal against the
9382/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009383static void checkObjCCollectionLiteralElement(Sema &S,
9384 QualType TargetElementType,
9385 Expr *Element,
9386 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009387 // Skip a bitcast to 'id' or qualified 'id'.
9388 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9389 if (ICE->getCastKind() == CK_BitCast &&
9390 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9391 Element = ICE->getSubExpr();
9392 }
9393
9394 QualType ElementType = Element->getType();
9395 ExprResult ElementResult(Element);
9396 if (ElementType->getAs<ObjCObjectPointerType>() &&
9397 S.CheckSingleAssignmentConstraints(TargetElementType,
9398 ElementResult,
9399 false, false)
9400 != Sema::Compatible) {
9401 S.Diag(Element->getLocStart(),
9402 diag::warn_objc_collection_literal_element)
9403 << ElementType << ElementKind << TargetElementType
9404 << Element->getSourceRange();
9405 }
9406
9407 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9408 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9409 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9410 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9411}
9412
9413/// Check an Objective-C array literal being converted to the given
9414/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009415static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9416 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009417 if (!S.NSArrayDecl)
9418 return;
9419
9420 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9421 if (!TargetObjCPtr)
9422 return;
9423
9424 if (TargetObjCPtr->isUnspecialized() ||
9425 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9426 != S.NSArrayDecl->getCanonicalDecl())
9427 return;
9428
9429 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9430 if (TypeArgs.size() != 1)
9431 return;
9432
9433 QualType TargetElementType = TypeArgs[0];
9434 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9435 checkObjCCollectionLiteralElement(S, TargetElementType,
9436 ArrayLiteral->getElement(I),
9437 0);
9438 }
9439}
9440
9441/// Check an Objective-C dictionary literal being converted to the given
9442/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009443static void
9444checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9445 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009446 if (!S.NSDictionaryDecl)
9447 return;
9448
9449 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9450 if (!TargetObjCPtr)
9451 return;
9452
9453 if (TargetObjCPtr->isUnspecialized() ||
9454 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9455 != S.NSDictionaryDecl->getCanonicalDecl())
9456 return;
9457
9458 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9459 if (TypeArgs.size() != 2)
9460 return;
9461
9462 QualType TargetKeyType = TypeArgs[0];
9463 QualType TargetObjectType = TypeArgs[1];
9464 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9465 auto Element = DictionaryLiteral->getKeyValueElement(I);
9466 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9467 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9468 }
9469}
9470
Richard Trieufc404c72016-02-05 23:02:38 +00009471// Helper function to filter out cases for constant width constant conversion.
9472// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009473static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9474 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009475 // If initializing from a constant, and the constant starts with '0',
9476 // then it is a binary, octal, or hexadecimal. Allow these constants
9477 // to fill all the bits, even if there is a sign change.
9478 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9479 const char FirstLiteralCharacter =
9480 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9481 if (FirstLiteralCharacter == '0')
9482 return false;
9483 }
9484
9485 // If the CC location points to a '{', and the type is char, then assume
9486 // assume it is an array initialization.
9487 if (CC.isValid() && T->isCharType()) {
9488 const char FirstContextCharacter =
9489 S.getSourceManager().getCharacterData(CC)[0];
9490 if (FirstContextCharacter == '{')
9491 return false;
9492 }
9493
9494 return true;
9495}
9496
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009497static void
9498CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9499 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009500 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009501
John McCallcc7e5bf2010-05-06 08:58:33 +00009502 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9503 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9504 if (Source == Target) return;
9505 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009506
Chandler Carruthc22845a2011-07-26 05:40:03 +00009507 // If the conversion context location is invalid don't complain. We also
9508 // don't want to emit a warning if the issue occurs from the expansion of
9509 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9510 // delay this check as long as possible. Once we detect we are in that
9511 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009512 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009513 return;
9514
Richard Trieu021baa32011-09-23 20:10:00 +00009515 // Diagnose implicit casts to bool.
9516 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9517 if (isa<StringLiteral>(E))
9518 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009519 // and expressions, for instance, assert(0 && "error here"), are
9520 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009521 return DiagnoseImpCast(S, E, T, CC,
9522 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009523 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9524 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9525 // This covers the literal expressions that evaluate to Objective-C
9526 // objects.
9527 return DiagnoseImpCast(S, E, T, CC,
9528 diag::warn_impcast_objective_c_literal_to_bool);
9529 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009530 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9531 // Warn on pointer to bool conversion that is always true.
9532 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9533 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009534 }
Richard Trieu021baa32011-09-23 20:10:00 +00009535 }
John McCall263a48b2010-01-04 23:31:57 +00009536
Douglas Gregor5054cb02015-07-07 03:58:22 +00009537 // Check implicit casts from Objective-C collection literals to specialized
9538 // collection types, e.g., NSArray<NSString *> *.
9539 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9540 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9541 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9542 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9543
John McCall263a48b2010-01-04 23:31:57 +00009544 // Strip vector types.
9545 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009546 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009547 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009548 return;
John McCallacf0ee52010-10-08 02:01:28 +00009549 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009550 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009551
9552 // If the vector cast is cast between two vectors of the same size, it is
9553 // a bitcast, not a conversion.
9554 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9555 return;
John McCall263a48b2010-01-04 23:31:57 +00009556
9557 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9558 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9559 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009560 if (auto VecTy = dyn_cast<VectorType>(Target))
9561 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009562
9563 // Strip complex types.
9564 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009565 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009566 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009567 return;
9568
Tim Northover02416372017-08-08 23:18:05 +00009569 return DiagnoseImpCast(S, E, T, CC,
9570 S.getLangOpts().CPlusPlus
9571 ? diag::err_impcast_complex_scalar
9572 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009573 }
John McCall263a48b2010-01-04 23:31:57 +00009574
9575 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9576 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9577 }
9578
9579 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9580 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9581
9582 // If the source is floating point...
9583 if (SourceBT && SourceBT->isFloatingPoint()) {
9584 // ...and the target is floating point...
9585 if (TargetBT && TargetBT->isFloatingPoint()) {
9586 // ...then warn if we're dropping FP rank.
9587
9588 // Builtin FP kinds are ordered by increasing FP rank.
9589 if (SourceBT->getKind() > TargetBT->getKind()) {
9590 // Don't warn about float constants that are precisely
9591 // representable in the target type.
9592 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009593 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009594 // Value might be a float, a float vector, or a float complex.
9595 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009596 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9597 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009598 return;
9599 }
9600
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009601 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009602 return;
9603
John McCallacf0ee52010-10-08 02:01:28 +00009604 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009605 }
9606 // ... or possibly if we're increasing rank, too
9607 else if (TargetBT->getKind() > SourceBT->getKind()) {
9608 if (S.SourceMgr.isInSystemMacro(CC))
9609 return;
9610
9611 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009612 }
9613 return;
9614 }
9615
Richard Trieube234c32016-04-21 21:04:55 +00009616 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009617 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009618 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009619 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009620
Richard Trieube234c32016-04-21 21:04:55 +00009621 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009622 }
John McCall263a48b2010-01-04 23:31:57 +00009623
Richard Smith54894fd2015-12-30 01:06:52 +00009624 // Detect the case where a call result is converted from floating-point to
9625 // to bool, and the final argument to the call is converted from bool, to
9626 // discover this typo:
9627 //
9628 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9629 //
9630 // FIXME: This is an incredibly special case; is there some more general
9631 // way to detect this class of misplaced-parentheses bug?
9632 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009633 // Check last argument of function call to see if it is an
9634 // implicit cast from a type matching the type the result
9635 // is being cast to.
9636 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009637 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009638 Expr *LastA = CEx->getArg(NumArgs - 1);
9639 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009640 if (isa<ImplicitCastExpr>(LastA) &&
9641 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009642 // Warn on this floating-point to bool conversion
9643 DiagnoseImpCast(S, E, T, CC,
9644 diag::warn_impcast_floating_point_to_bool);
9645 }
9646 }
9647 }
John McCall263a48b2010-01-04 23:31:57 +00009648 return;
9649 }
9650
Richard Trieu5b993502014-10-15 03:42:06 +00009651 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009652
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009653 S.DiscardMisalignedMemberAddress(Target, E);
9654
David Blaikie9366d2b2012-06-19 21:19:06 +00009655 if (!Source->isIntegerType() || !Target->isIntegerType())
9656 return;
9657
David Blaikie7555b6a2012-05-15 16:56:36 +00009658 // TODO: remove this early return once the false positives for constant->bool
9659 // in templates, macros, etc, are reduced or removed.
9660 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9661 return;
9662
John McCallcc7e5bf2010-05-06 08:58:33 +00009663 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009664 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009665
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009666 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009667 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009668 // TODO: this should happen for bitfield stores, too.
9669 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009670 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009671 if (S.SourceMgr.isInSystemMacro(CC))
9672 return;
9673
John McCall18a2c2c2010-11-09 22:22:12 +00009674 std::string PrettySourceValue = Value.toString(10);
9675 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009676
Ted Kremenek33ba9952011-10-22 02:37:33 +00009677 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9678 S.PDiag(diag::warn_impcast_integer_precision_constant)
9679 << PrettySourceValue << PrettyTargetValue
9680 << E->getType() << T << E->getSourceRange()
9681 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009682 return;
9683 }
9684
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009685 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9686 if (S.SourceMgr.isInSystemMacro(CC))
9687 return;
9688
David Blaikie9455da02012-04-12 22:40:54 +00009689 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009690 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9691 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009692 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009693 }
9694
Richard Trieudcb55572016-01-29 23:51:16 +00009695 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9696 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9697 // Warn when doing a signed to signed conversion, warn if the positive
9698 // source value is exactly the width of the target type, which will
9699 // cause a negative value to be stored.
9700
9701 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009702 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9703 !S.SourceMgr.isInSystemMacro(CC)) {
9704 if (isSameWidthConstantConversion(S, E, T, CC)) {
9705 std::string PrettySourceValue = Value.toString(10);
9706 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009707
Richard Trieufc404c72016-02-05 23:02:38 +00009708 S.DiagRuntimeBehavior(
9709 E->getExprLoc(), E,
9710 S.PDiag(diag::warn_impcast_integer_precision_constant)
9711 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9712 << E->getSourceRange() << clang::SourceRange(CC));
9713 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009714 }
9715 }
Richard Trieufc404c72016-02-05 23:02:38 +00009716
Richard Trieudcb55572016-01-29 23:51:16 +00009717 // Fall through for non-constants to give a sign conversion warning.
9718 }
9719
John McCallcc7e5bf2010-05-06 08:58:33 +00009720 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9721 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9722 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009723 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009724 return;
9725
John McCallcc7e5bf2010-05-06 08:58:33 +00009726 unsigned DiagID = diag::warn_impcast_integer_sign;
9727
9728 // Traditionally, gcc has warned about this under -Wsign-compare.
9729 // We also want to warn about it in -Wconversion.
9730 // So if -Wconversion is off, use a completely identical diagnostic
9731 // in the sign-compare group.
9732 // The conditional-checking code will
9733 if (ICContext) {
9734 DiagID = diag::warn_impcast_integer_sign_conditional;
9735 *ICContext = true;
9736 }
9737
John McCallacf0ee52010-10-08 02:01:28 +00009738 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009739 }
9740
Douglas Gregora78f1932011-02-22 02:45:07 +00009741 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009742 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9743 // type, to give us better diagnostics.
9744 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009745 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009746 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9747 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9748 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9749 SourceType = S.Context.getTypeDeclType(Enum);
9750 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9751 }
9752 }
9753
Douglas Gregora78f1932011-02-22 02:45:07 +00009754 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9755 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009756 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9757 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009758 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009759 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009760 return;
9761
Douglas Gregor364f7db2011-03-12 00:14:31 +00009762 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009763 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009764 }
John McCall263a48b2010-01-04 23:31:57 +00009765}
9766
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009767static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9768 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009769
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009770static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9771 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009772 E = E->IgnoreParenImpCasts();
9773
9774 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009775 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009776
John McCallacf0ee52010-10-08 02:01:28 +00009777 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009778 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009779 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009780}
9781
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009782static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9783 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009784 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009785
9786 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009787 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9788 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009789
9790 // If -Wconversion would have warned about either of the candidates
9791 // for a signedness conversion to the context type...
9792 if (!Suspicious) return;
9793
9794 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009795 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009796 return;
9797
John McCallcc7e5bf2010-05-06 08:58:33 +00009798 // ...then check whether it would have warned about either of the
9799 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009800 if (E->getType() == T) return;
9801
9802 Suspicious = false;
9803 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9804 E->getType(), CC, &Suspicious);
9805 if (!Suspicious)
9806 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009807 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009808}
9809
Richard Trieu65724892014-11-15 06:37:39 +00009810/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9811/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009812static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009813 if (S.getLangOpts().Bool)
9814 return;
9815 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9816}
9817
John McCallcc7e5bf2010-05-06 08:58:33 +00009818/// AnalyzeImplicitConversions - Find and report any interesting
9819/// implicit conversions in the given expression. There are a couple
9820/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009821static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9822 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009823 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009824 Expr *E = OrigE->IgnoreParenImpCasts();
9825
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009826 if (E->isTypeDependent() || E->isValueDependent())
9827 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009828
John McCallcc7e5bf2010-05-06 08:58:33 +00009829 // For conditional operators, we analyze the arguments as if they
9830 // were being fed directly into the output.
9831 if (isa<ConditionalOperator>(E)) {
9832 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009833 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009834 return;
9835 }
9836
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009837 // Check implicit argument conversions for function calls.
9838 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9839 CheckImplicitArgumentConversions(S, Call, CC);
9840
John McCallcc7e5bf2010-05-06 08:58:33 +00009841 // Go ahead and check any implicit conversions we might have skipped.
9842 // The non-canonical typecheck is just an optimization;
9843 // CheckImplicitConversion will filter out dead implicit conversions.
9844 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009845 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009846
9847 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009848
9849 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9850 // The bound subexpressions in a PseudoObjectExpr are not reachable
9851 // as transitive children.
9852 // FIXME: Use a more uniform representation for this.
9853 for (auto *SE : POE->semantics())
9854 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9855 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009856 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009857
John McCallcc7e5bf2010-05-06 08:58:33 +00009858 // Skip past explicit casts.
9859 if (isa<ExplicitCastExpr>(E)) {
9860 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009861 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009862 }
9863
John McCalld2a53122010-11-09 23:24:47 +00009864 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9865 // Do a somewhat different check with comparison operators.
9866 if (BO->isComparisonOp())
9867 return AnalyzeComparison(S, BO);
9868
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009869 // And with simple assignments.
9870 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009871 return AnalyzeAssignment(S, BO);
9872 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009873
9874 // These break the otherwise-useful invariant below. Fortunately,
9875 // we don't really need to recurse into them, because any internal
9876 // expressions should have been analyzed already when they were
9877 // built into statements.
9878 if (isa<StmtExpr>(E)) return;
9879
9880 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009881 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009882
9883 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009884 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009885 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009886 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009887 for (Stmt *SubStmt : E->children()) {
9888 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009889 if (!ChildExpr)
9890 continue;
9891
Richard Trieu955231d2014-01-25 01:10:35 +00009892 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009893 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009894 // Ignore checking string literals that are in logical and operators.
9895 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009896 continue;
9897 AnalyzeImplicitConversions(S, ChildExpr, CC);
9898 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009899
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009900 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009901 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9902 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009903 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009904
9905 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9906 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009907 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009908 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009909
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009910 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9911 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009912 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009913}
9914
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009915/// Diagnose integer type and any valid implicit convertion to it.
9916static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9917 // Taking into account implicit conversions,
9918 // allow any integer.
9919 if (!E->getType()->isIntegerType()) {
9920 S.Diag(E->getLocStart(),
9921 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9922 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009923 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009924 // Potentially emit standard warnings for implicit conversions if enabled
9925 // using -Wconversion.
9926 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9927 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009928}
9929
Richard Trieuc1888e02014-06-28 23:25:37 +00009930// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9931// Returns true when emitting a warning about taking the address of a reference.
9932static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009933 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009934 E = E->IgnoreParenImpCasts();
9935
9936 const FunctionDecl *FD = nullptr;
9937
9938 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9939 if (!DRE->getDecl()->getType()->isReferenceType())
9940 return false;
9941 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9942 if (!M->getMemberDecl()->getType()->isReferenceType())
9943 return false;
9944 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009945 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009946 return false;
9947 FD = Call->getDirectCallee();
9948 } else {
9949 return false;
9950 }
9951
9952 SemaRef.Diag(E->getExprLoc(), PD);
9953
9954 // If possible, point to location of function.
9955 if (FD) {
9956 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9957 }
9958
9959 return true;
9960}
9961
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009962// Returns true if the SourceLocation is expanded from any macro body.
9963// Returns false if the SourceLocation is invalid, is from not in a macro
9964// expansion, or is from expanded from a top-level macro argument.
9965static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9966 if (Loc.isInvalid())
9967 return false;
9968
9969 while (Loc.isMacroID()) {
9970 if (SM.isMacroBodyExpansion(Loc))
9971 return true;
9972 Loc = SM.getImmediateMacroCallerLoc(Loc);
9973 }
9974
9975 return false;
9976}
9977
Richard Trieu3bb8b562014-02-26 02:36:06 +00009978/// \brief Diagnose pointers that are always non-null.
9979/// \param E the expression containing the pointer
9980/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9981/// compared to a null pointer
9982/// \param IsEqual True when the comparison is equal to a null pointer
9983/// \param Range Extra SourceRange to highlight in the diagnostic
9984void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9985 Expr::NullPointerConstantKind NullKind,
9986 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009987 if (!E)
9988 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009989
9990 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009991 if (E->getExprLoc().isMacroID()) {
9992 const SourceManager &SM = getSourceManager();
9993 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9994 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009995 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009996 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009997 E = E->IgnoreImpCasts();
9998
9999 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10000
Richard Trieuf7432752014-06-06 21:39:26 +000010001 if (isa<CXXThisExpr>(E)) {
10002 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10003 : diag::warn_this_bool_conversion;
10004 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10005 return;
10006 }
10007
Richard Trieu3bb8b562014-02-26 02:36:06 +000010008 bool IsAddressOf = false;
10009
10010 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10011 if (UO->getOpcode() != UO_AddrOf)
10012 return;
10013 IsAddressOf = true;
10014 E = UO->getSubExpr();
10015 }
10016
Richard Trieuc1888e02014-06-28 23:25:37 +000010017 if (IsAddressOf) {
10018 unsigned DiagID = IsCompare
10019 ? diag::warn_address_of_reference_null_compare
10020 : diag::warn_address_of_reference_bool_conversion;
10021 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10022 << IsEqual;
10023 if (CheckForReference(*this, E, PD)) {
10024 return;
10025 }
10026 }
10027
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010028 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10029 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010030 std::string Str;
10031 llvm::raw_string_ostream S(Str);
10032 E->printPretty(S, nullptr, getPrintingPolicy());
10033 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10034 : diag::warn_cast_nonnull_to_bool;
10035 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10036 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010037 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010038 };
10039
10040 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10041 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10042 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010043 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10044 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010045 return;
10046 }
10047 }
10048 }
10049
Richard Trieu3bb8b562014-02-26 02:36:06 +000010050 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010051 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010052 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10053 D = R->getDecl();
10054 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10055 D = M->getMemberDecl();
10056 }
10057
10058 // Weak Decls can be null.
10059 if (!D || D->isWeak())
10060 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010061
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010062 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010063 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10064 if (getCurFunction() &&
10065 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010066 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10067 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010068 return;
10069 }
10070
10071 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010072 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010073 assert(ParamIter != FD->param_end());
10074 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10075
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010076 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10077 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010078 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010079 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010080 }
George Burgess IV850269a2015-12-08 22:02:00 +000010081
10082 for (unsigned ArgNo : NonNull->args()) {
10083 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010084 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010085 return;
10086 }
George Burgess IV850269a2015-12-08 22:02:00 +000010087 }
10088 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010089 }
10090 }
George Burgess IV850269a2015-12-08 22:02:00 +000010091 }
10092
Richard Trieu3bb8b562014-02-26 02:36:06 +000010093 QualType T = D->getType();
10094 const bool IsArray = T->isArrayType();
10095 const bool IsFunction = T->isFunctionType();
10096
Richard Trieuc1888e02014-06-28 23:25:37 +000010097 // Address of function is used to silence the function warning.
10098 if (IsAddressOf && IsFunction) {
10099 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010100 }
10101
10102 // Found nothing.
10103 if (!IsAddressOf && !IsFunction && !IsArray)
10104 return;
10105
10106 // Pretty print the expression for the diagnostic.
10107 std::string Str;
10108 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010109 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010110
10111 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10112 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010113 enum {
10114 AddressOf,
10115 FunctionPointer,
10116 ArrayPointer
10117 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010118 if (IsAddressOf)
10119 DiagType = AddressOf;
10120 else if (IsFunction)
10121 DiagType = FunctionPointer;
10122 else if (IsArray)
10123 DiagType = ArrayPointer;
10124 else
10125 llvm_unreachable("Could not determine diagnostic.");
10126 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10127 << Range << IsEqual;
10128
10129 if (!IsFunction)
10130 return;
10131
10132 // Suggest '&' to silence the function warning.
10133 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10134 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10135
10136 // Check to see if '()' fixit should be emitted.
10137 QualType ReturnType;
10138 UnresolvedSet<4> NonTemplateOverloads;
10139 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10140 if (ReturnType.isNull())
10141 return;
10142
10143 if (IsCompare) {
10144 // There are two cases here. If there is null constant, the only suggest
10145 // for a pointer return type. If the null is 0, then suggest if the return
10146 // type is a pointer or an integer type.
10147 if (!ReturnType->isPointerType()) {
10148 if (NullKind == Expr::NPCK_ZeroExpression ||
10149 NullKind == Expr::NPCK_ZeroLiteral) {
10150 if (!ReturnType->isIntegerType())
10151 return;
10152 } else {
10153 return;
10154 }
10155 }
10156 } else { // !IsCompare
10157 // For function to bool, only suggest if the function pointer has bool
10158 // return type.
10159 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10160 return;
10161 }
10162 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010163 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010164}
10165
John McCallcc7e5bf2010-05-06 08:58:33 +000010166/// Diagnoses "dangerous" implicit conversions within the given
10167/// expression (which is a full expression). Implements -Wconversion
10168/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010169///
10170/// \param CC the "context" location of the implicit conversion, i.e.
10171/// the most location of the syntactic entity requiring the implicit
10172/// conversion
10173void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010174 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010175 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010176 return;
10177
10178 // Don't diagnose for value- or type-dependent expressions.
10179 if (E->isTypeDependent() || E->isValueDependent())
10180 return;
10181
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010182 // Check for array bounds violations in cases where the check isn't triggered
10183 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10184 // ArraySubscriptExpr is on the RHS of a variable initialization.
10185 CheckArrayAccess(E);
10186
John McCallacf0ee52010-10-08 02:01:28 +000010187 // This is not the right CC for (e.g.) a variable initialization.
10188 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010189}
10190
Richard Trieu65724892014-11-15 06:37:39 +000010191/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10192/// Input argument E is a logical expression.
10193void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10194 ::CheckBoolLikeConversion(*this, E, CC);
10195}
10196
Richard Smith9f7df0c2017-06-26 23:19:32 +000010197/// Diagnose when expression is an integer constant expression and its evaluation
10198/// results in integer overflow
10199void Sema::CheckForIntOverflow (Expr *E) {
10200 // Use a work list to deal with nested struct initializers.
10201 SmallVector<Expr *, 2> Exprs(1, E);
10202
10203 do {
10204 Expr *E = Exprs.pop_back_val();
10205
10206 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10207 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10208 continue;
10209 }
10210
10211 if (auto InitList = dyn_cast<InitListExpr>(E))
10212 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10213
10214 if (isa<ObjCBoxedExpr>(E))
10215 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10216 } while (!Exprs.empty());
10217}
10218
Richard Smithc406cb72013-01-17 01:17:56 +000010219namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010220
Richard Smithc406cb72013-01-17 01:17:56 +000010221/// \brief Visitor for expressions which looks for unsequenced operations on the
10222/// same object.
10223class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010224 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010225
Richard Smithc406cb72013-01-17 01:17:56 +000010226 /// \brief A tree of sequenced regions within an expression. Two regions are
10227 /// unsequenced if one is an ancestor or a descendent of the other. When we
10228 /// finish processing an expression with sequencing, such as a comma
10229 /// expression, we fold its tree nodes into its parent, since they are
10230 /// unsequenced with respect to nodes we will visit later.
10231 class SequenceTree {
10232 struct Value {
10233 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10234 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010235 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010236 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010237 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010238
10239 public:
10240 /// \brief A region within an expression which may be sequenced with respect
10241 /// to some other region.
10242 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010243 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010244
10245 unsigned Index = 0;
10246
10247 explicit Seq(unsigned N) : Index(N) {}
10248
Richard Smithc406cb72013-01-17 01:17:56 +000010249 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010250 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010251 };
10252
10253 SequenceTree() { Values.push_back(Value(0)); }
10254 Seq root() const { return Seq(0); }
10255
10256 /// \brief Create a new sequence of operations, which is an unsequenced
10257 /// subset of \p Parent. This sequence of operations is sequenced with
10258 /// respect to other children of \p Parent.
10259 Seq allocate(Seq Parent) {
10260 Values.push_back(Value(Parent.Index));
10261 return Seq(Values.size() - 1);
10262 }
10263
10264 /// \brief Merge a sequence of operations into its parent.
10265 void merge(Seq S) {
10266 Values[S.Index].Merged = true;
10267 }
10268
10269 /// \brief Determine whether two operations are unsequenced. This operation
10270 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10271 /// should have been merged into its parent as appropriate.
10272 bool isUnsequenced(Seq Cur, Seq Old) {
10273 unsigned C = representative(Cur.Index);
10274 unsigned Target = representative(Old.Index);
10275 while (C >= Target) {
10276 if (C == Target)
10277 return true;
10278 C = Values[C].Parent;
10279 }
10280 return false;
10281 }
10282
10283 private:
10284 /// \brief Pick a representative for a sequence.
10285 unsigned representative(unsigned K) {
10286 if (Values[K].Merged)
10287 // Perform path compression as we go.
10288 return Values[K].Parent = representative(Values[K].Parent);
10289 return K;
10290 }
10291 };
10292
10293 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010294 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010295
10296 /// Different flavors of object usage which we track. We only track the
10297 /// least-sequenced usage of each kind.
10298 enum UsageKind {
10299 /// A read of an object. Multiple unsequenced reads are OK.
10300 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010301
Richard Smithc406cb72013-01-17 01:17:56 +000010302 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010303 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010304 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010305
Richard Smithc406cb72013-01-17 01:17:56 +000010306 /// A modification of an object which is not sequenced before the value
10307 /// computation of the expression, such as n++.
10308 UK_ModAsSideEffect,
10309
10310 UK_Count = UK_ModAsSideEffect + 1
10311 };
10312
10313 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010314 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010315 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010316
10317 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010318 };
10319
10320 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010321 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010322
Richard Smithc406cb72013-01-17 01:17:56 +000010323 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010324 bool Diagnosed = false;
10325
10326 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010327 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010328 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010329
10330 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010331
Richard Smithc406cb72013-01-17 01:17:56 +000010332 /// Sequenced regions within the expression.
10333 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010334
Richard Smithc406cb72013-01-17 01:17:56 +000010335 /// Declaration modifications and references which we have seen.
10336 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010337
Richard Smithc406cb72013-01-17 01:17:56 +000010338 /// The region we are currently within.
10339 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010340
Richard Smithc406cb72013-01-17 01:17:56 +000010341 /// Filled in with declarations which were modified as a side-effect
10342 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010343 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10344
Richard Smithd33f5202013-01-17 23:18:09 +000010345 /// Expressions to check later. We defer checking these to reduce
10346 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010347 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010348
10349 /// RAII object wrapping the visitation of a sequenced subexpression of an
10350 /// expression. At the end of this process, the side-effects of the evaluation
10351 /// become sequenced with respect to the value computation of the result, so
10352 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10353 /// UK_ModAsValue.
10354 struct SequencedSubexpression {
10355 SequencedSubexpression(SequenceChecker &Self)
10356 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10357 Self.ModAsSideEffect = &ModAsSideEffect;
10358 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010359
Richard Smithc406cb72013-01-17 01:17:56 +000010360 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010361 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10362 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010363 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010364 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10365 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010366 }
10367 Self.ModAsSideEffect = OldModAsSideEffect;
10368 }
10369
10370 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010371 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010372 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010373 };
10374
Richard Smith40238f02013-06-20 22:21:56 +000010375 /// RAII object wrapping the visitation of a subexpression which we might
10376 /// choose to evaluate as a constant. If any subexpression is evaluated and
10377 /// found to be non-constant, this allows us to suppress the evaluation of
10378 /// the outer expression.
10379 class EvaluationTracker {
10380 public:
10381 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010382 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010383 Self.EvalTracker = this;
10384 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010385
Richard Smith40238f02013-06-20 22:21:56 +000010386 ~EvaluationTracker() {
10387 Self.EvalTracker = Prev;
10388 if (Prev)
10389 Prev->EvalOK &= EvalOK;
10390 }
10391
10392 bool evaluate(const Expr *E, bool &Result) {
10393 if (!EvalOK || E->isValueDependent())
10394 return false;
10395 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10396 return EvalOK;
10397 }
10398
10399 private:
10400 SequenceChecker &Self;
10401 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010402 bool EvalOK = true;
10403 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010404
Richard Smithc406cb72013-01-17 01:17:56 +000010405 /// \brief Find the object which is produced by the specified expression,
10406 /// if any.
10407 Object getObject(Expr *E, bool Mod) const {
10408 E = E->IgnoreParenCasts();
10409 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10410 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10411 return getObject(UO->getSubExpr(), Mod);
10412 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10413 if (BO->getOpcode() == BO_Comma)
10414 return getObject(BO->getRHS(), Mod);
10415 if (Mod && BO->isAssignmentOp())
10416 return getObject(BO->getLHS(), Mod);
10417 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10418 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10419 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10420 return ME->getMemberDecl();
10421 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10422 // FIXME: If this is a reference, map through to its value.
10423 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010424 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010425 }
10426
10427 /// \brief Note that an object was modified or used by an expression.
10428 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10429 Usage &U = UI.Uses[UK];
10430 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10431 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10432 ModAsSideEffect->push_back(std::make_pair(O, U));
10433 U.Use = Ref;
10434 U.Seq = Region;
10435 }
10436 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010437
Richard Smithc406cb72013-01-17 01:17:56 +000010438 /// \brief Check whether a modification or use conflicts with a prior usage.
10439 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10440 bool IsModMod) {
10441 if (UI.Diagnosed)
10442 return;
10443
10444 const Usage &U = UI.Uses[OtherKind];
10445 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10446 return;
10447
10448 Expr *Mod = U.Use;
10449 Expr *ModOrUse = Ref;
10450 if (OtherKind == UK_Use)
10451 std::swap(Mod, ModOrUse);
10452
10453 SemaRef.Diag(Mod->getExprLoc(),
10454 IsModMod ? diag::warn_unsequenced_mod_mod
10455 : diag::warn_unsequenced_mod_use)
10456 << O << SourceRange(ModOrUse->getExprLoc());
10457 UI.Diagnosed = true;
10458 }
10459
10460 void notePreUse(Object O, Expr *Use) {
10461 UsageInfo &U = UsageMap[O];
10462 // Uses conflict with other modifications.
10463 checkUsage(O, U, Use, UK_ModAsValue, false);
10464 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010465
Richard Smithc406cb72013-01-17 01:17:56 +000010466 void notePostUse(Object O, Expr *Use) {
10467 UsageInfo &U = UsageMap[O];
10468 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10469 addUsage(U, O, Use, UK_Use);
10470 }
10471
10472 void notePreMod(Object O, Expr *Mod) {
10473 UsageInfo &U = UsageMap[O];
10474 // Modifications conflict with other modifications and with uses.
10475 checkUsage(O, U, Mod, UK_ModAsValue, true);
10476 checkUsage(O, U, Mod, UK_Use, false);
10477 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010478
Richard Smithc406cb72013-01-17 01:17:56 +000010479 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10480 UsageInfo &U = UsageMap[O];
10481 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10482 addUsage(U, O, Use, UK);
10483 }
10484
10485public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010486 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010487 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010488 Visit(E);
10489 }
10490
10491 void VisitStmt(Stmt *S) {
10492 // Skip all statements which aren't expressions for now.
10493 }
10494
10495 void VisitExpr(Expr *E) {
10496 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010497 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010498 }
10499
10500 void VisitCastExpr(CastExpr *E) {
10501 Object O = Object();
10502 if (E->getCastKind() == CK_LValueToRValue)
10503 O = getObject(E->getSubExpr(), false);
10504
10505 if (O)
10506 notePreUse(O, E);
10507 VisitExpr(E);
10508 if (O)
10509 notePostUse(O, E);
10510 }
10511
10512 void VisitBinComma(BinaryOperator *BO) {
10513 // C++11 [expr.comma]p1:
10514 // Every value computation and side effect associated with the left
10515 // expression is sequenced before every value computation and side
10516 // effect associated with the right expression.
10517 SequenceTree::Seq LHS = Tree.allocate(Region);
10518 SequenceTree::Seq RHS = Tree.allocate(Region);
10519 SequenceTree::Seq OldRegion = Region;
10520
10521 {
10522 SequencedSubexpression SeqLHS(*this);
10523 Region = LHS;
10524 Visit(BO->getLHS());
10525 }
10526
10527 Region = RHS;
10528 Visit(BO->getRHS());
10529
10530 Region = OldRegion;
10531
10532 // Forget that LHS and RHS are sequenced. They are both unsequenced
10533 // with respect to other stuff.
10534 Tree.merge(LHS);
10535 Tree.merge(RHS);
10536 }
10537
10538 void VisitBinAssign(BinaryOperator *BO) {
10539 // The modification is sequenced after the value computation of the LHS
10540 // and RHS, so check it before inspecting the operands and update the
10541 // map afterwards.
10542 Object O = getObject(BO->getLHS(), true);
10543 if (!O)
10544 return VisitExpr(BO);
10545
10546 notePreMod(O, BO);
10547
10548 // C++11 [expr.ass]p7:
10549 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10550 // only once.
10551 //
10552 // Therefore, for a compound assignment operator, O is considered used
10553 // everywhere except within the evaluation of E1 itself.
10554 if (isa<CompoundAssignOperator>(BO))
10555 notePreUse(O, BO);
10556
10557 Visit(BO->getLHS());
10558
10559 if (isa<CompoundAssignOperator>(BO))
10560 notePostUse(O, BO);
10561
10562 Visit(BO->getRHS());
10563
Richard Smith83e37bee2013-06-26 23:16:51 +000010564 // C++11 [expr.ass]p1:
10565 // the assignment is sequenced [...] before the value computation of the
10566 // assignment expression.
10567 // C11 6.5.16/3 has no such rule.
10568 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10569 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010570 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010571
Richard Smithc406cb72013-01-17 01:17:56 +000010572 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10573 VisitBinAssign(CAO);
10574 }
10575
10576 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10577 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10578 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10579 Object O = getObject(UO->getSubExpr(), true);
10580 if (!O)
10581 return VisitExpr(UO);
10582
10583 notePreMod(O, UO);
10584 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010585 // C++11 [expr.pre.incr]p1:
10586 // the expression ++x is equivalent to x+=1
10587 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10588 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010589 }
10590
10591 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10592 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10593 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10594 Object O = getObject(UO->getSubExpr(), true);
10595 if (!O)
10596 return VisitExpr(UO);
10597
10598 notePreMod(O, UO);
10599 Visit(UO->getSubExpr());
10600 notePostMod(O, UO, UK_ModAsSideEffect);
10601 }
10602
10603 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10604 void VisitBinLOr(BinaryOperator *BO) {
10605 // The side-effects of the LHS of an '&&' are sequenced before the
10606 // value computation of the RHS, and hence before the value computation
10607 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10608 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010609 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010610 {
10611 SequencedSubexpression Sequenced(*this);
10612 Visit(BO->getLHS());
10613 }
10614
10615 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010616 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010617 if (!Result)
10618 Visit(BO->getRHS());
10619 } else {
10620 // Check for unsequenced operations in the RHS, treating it as an
10621 // entirely separate evaluation.
10622 //
10623 // FIXME: If there are operations in the RHS which are unsequenced
10624 // with respect to operations outside the RHS, and those operations
10625 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010626 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010627 }
Richard Smithc406cb72013-01-17 01:17:56 +000010628 }
10629 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010630 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010631 {
10632 SequencedSubexpression Sequenced(*this);
10633 Visit(BO->getLHS());
10634 }
10635
10636 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010637 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010638 if (Result)
10639 Visit(BO->getRHS());
10640 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010641 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010642 }
Richard Smithc406cb72013-01-17 01:17:56 +000010643 }
10644
10645 // Only visit the condition, unless we can be sure which subexpression will
10646 // be chosen.
10647 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010648 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010649 {
10650 SequencedSubexpression Sequenced(*this);
10651 Visit(CO->getCond());
10652 }
Richard Smithc406cb72013-01-17 01:17:56 +000010653
10654 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010655 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010656 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010657 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010658 WorkList.push_back(CO->getTrueExpr());
10659 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010660 }
Richard Smithc406cb72013-01-17 01:17:56 +000010661 }
10662
Richard Smithe3dbfe02013-06-30 10:40:20 +000010663 void VisitCallExpr(CallExpr *CE) {
10664 // C++11 [intro.execution]p15:
10665 // When calling a function [...], every value computation and side effect
10666 // associated with any argument expression, or with the postfix expression
10667 // designating the called function, is sequenced before execution of every
10668 // expression or statement in the body of the function [and thus before
10669 // the value computation of its result].
10670 SequencedSubexpression Sequenced(*this);
10671 Base::VisitCallExpr(CE);
10672
10673 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10674 }
10675
Richard Smithc406cb72013-01-17 01:17:56 +000010676 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010677 // This is a call, so all subexpressions are sequenced before the result.
10678 SequencedSubexpression Sequenced(*this);
10679
Richard Smithc406cb72013-01-17 01:17:56 +000010680 if (!CCE->isListInitialization())
10681 return VisitExpr(CCE);
10682
10683 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010684 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010685 SequenceTree::Seq Parent = Region;
10686 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10687 E = CCE->arg_end();
10688 I != E; ++I) {
10689 Region = Tree.allocate(Parent);
10690 Elts.push_back(Region);
10691 Visit(*I);
10692 }
10693
10694 // Forget that the initializers are sequenced.
10695 Region = Parent;
10696 for (unsigned I = 0; I < Elts.size(); ++I)
10697 Tree.merge(Elts[I]);
10698 }
10699
10700 void VisitInitListExpr(InitListExpr *ILE) {
10701 if (!SemaRef.getLangOpts().CPlusPlus11)
10702 return VisitExpr(ILE);
10703
10704 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010705 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010706 SequenceTree::Seq Parent = Region;
10707 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10708 Expr *E = ILE->getInit(I);
10709 if (!E) continue;
10710 Region = Tree.allocate(Parent);
10711 Elts.push_back(Region);
10712 Visit(E);
10713 }
10714
10715 // Forget that the initializers are sequenced.
10716 Region = Parent;
10717 for (unsigned I = 0; I < Elts.size(); ++I)
10718 Tree.merge(Elts[I]);
10719 }
10720};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010721
10722} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010723
10724void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010725 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010726 WorkList.push_back(E);
10727 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010728 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010729 SequenceChecker(*this, Item, WorkList);
10730 }
Richard Smithc406cb72013-01-17 01:17:56 +000010731}
10732
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010733void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10734 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010735 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010736 if (!E->isInstantiationDependent())
10737 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010738 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010739 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010740 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010741}
10742
John McCall1f425642010-11-11 03:21:53 +000010743void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10744 FieldDecl *BitField,
10745 Expr *Init) {
10746 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10747}
10748
David Majnemer61a5bbf2015-04-07 22:08:51 +000010749static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10750 SourceLocation Loc) {
10751 if (!PType->isVariablyModifiedType())
10752 return;
10753 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10754 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10755 return;
10756 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010757 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10758 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10759 return;
10760 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010761 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10762 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10763 return;
10764 }
10765
10766 const ArrayType *AT = S.Context.getAsArrayType(PType);
10767 if (!AT)
10768 return;
10769
10770 if (AT->getSizeModifier() != ArrayType::Star) {
10771 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10772 return;
10773 }
10774
10775 S.Diag(Loc, diag::err_array_star_in_function_definition);
10776}
10777
Mike Stump0c2ec772010-01-21 03:59:47 +000010778/// CheckParmsForFunctionDef - Check that the parameters of the given
10779/// function are appropriate for the definition of a function. This
10780/// takes care of any checks that cannot be performed on the
10781/// declaration itself, e.g., that the types of each of the function
10782/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010783bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010784 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010785 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010786 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010787 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10788 // function declarator that is part of a function definition of
10789 // that function shall not have incomplete type.
10790 //
10791 // This is also C++ [dcl.fct]p6.
10792 if (!Param->isInvalidDecl() &&
10793 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010794 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010795 Param->setInvalidDecl();
10796 HasInvalidParm = true;
10797 }
10798
10799 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10800 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010801 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010802 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010803 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010804 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010805 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010806
10807 // C99 6.7.5.3p12:
10808 // If the function declarator is not part of a definition of that
10809 // function, parameters may have incomplete type and may use the [*]
10810 // notation in their sequences of declarator specifiers to specify
10811 // variable length array types.
10812 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010813 // FIXME: This diagnostic should point the '[*]' if source-location
10814 // information is added for it.
10815 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010816
Akira Hatanaka02914dc2018-02-05 20:23:22 +000010817 // If the parameter is a c++ class type and it has to be destructed in the
10818 // callee function, declare the destructor so that it can be called by the
10819 // callee function. Do not perfom any direct access check on the dtor here.
10820 if (!Param->isInvalidDecl()) {
10821 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
10822 if (!ClassDecl->isInvalidDecl() &&
10823 !ClassDecl->hasIrrelevantDestructor() &&
10824 !ClassDecl->isDependentContext() &&
10825 Context.isParamDestroyedInCallee(Param->getType())) {
10826 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10827 MarkFunctionReferenced(Param->getLocation(), Destructor);
10828 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010829 }
10830 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010831 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010832
10833 // Parameters with the pass_object_size attribute only need to be marked
10834 // constant at function definitions. Because we lack information about
10835 // whether we're on a declaration or definition when we're instantiating the
10836 // attribute, we need to check for constness here.
10837 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10838 if (!Param->getType().isConstQualified())
10839 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10840 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010841 }
10842
10843 return HasInvalidParm;
10844}
John McCall2b5c1b22010-08-12 21:44:57 +000010845
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010846/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10847/// or MemberExpr.
10848static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10849 ASTContext &Context) {
10850 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10851 return Context.getDeclAlign(DRE->getDecl());
10852
10853 if (const auto *ME = dyn_cast<MemberExpr>(E))
10854 return Context.getDeclAlign(ME->getMemberDecl());
10855
10856 return TypeAlign;
10857}
10858
John McCall2b5c1b22010-08-12 21:44:57 +000010859/// CheckCastAlign - Implements -Wcast-align, which warns when a
10860/// pointer cast increases the alignment requirements.
10861void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10862 // This is actually a lot of work to potentially be doing on every
10863 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010864 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010865 return;
10866
10867 // Ignore dependent types.
10868 if (T->isDependentType() || Op->getType()->isDependentType())
10869 return;
10870
10871 // Require that the destination be a pointer type.
10872 const PointerType *DestPtr = T->getAs<PointerType>();
10873 if (!DestPtr) return;
10874
10875 // If the destination has alignment 1, we're done.
10876 QualType DestPointee = DestPtr->getPointeeType();
10877 if (DestPointee->isIncompleteType()) return;
10878 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10879 if (DestAlign.isOne()) return;
10880
10881 // Require that the source be a pointer type.
10882 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10883 if (!SrcPtr) return;
10884 QualType SrcPointee = SrcPtr->getPointeeType();
10885
10886 // Whitelist casts from cv void*. We already implicitly
10887 // whitelisted casts to cv void*, since they have alignment 1.
10888 // Also whitelist casts involving incomplete types, which implicitly
10889 // includes 'void'.
10890 if (SrcPointee->isIncompleteType()) return;
10891
10892 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010893
10894 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10895 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10896 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10897 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10898 if (UO->getOpcode() == UO_AddrOf)
10899 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10900 }
10901
John McCall2b5c1b22010-08-12 21:44:57 +000010902 if (SrcAlign >= DestAlign) return;
10903
10904 Diag(TRange.getBegin(), diag::warn_cast_align)
10905 << Op->getType() << T
10906 << static_cast<unsigned>(SrcAlign.getQuantity())
10907 << static_cast<unsigned>(DestAlign.getQuantity())
10908 << TRange << Op->getSourceRange();
10909}
10910
Chandler Carruth28389f02011-08-05 09:10:50 +000010911/// \brief Check whether this array fits the idiom of a size-one tail padded
10912/// array member of a struct.
10913///
10914/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10915/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010916static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010917 const NamedDecl *ND) {
10918 if (Size != 1 || !ND) return false;
10919
10920 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10921 if (!FD) return false;
10922
10923 // Don't consider sizes resulting from macro expansions or template argument
10924 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010925
10926 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010927 while (TInfo) {
10928 TypeLoc TL = TInfo->getTypeLoc();
10929 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010930 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10931 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010932 TInfo = TDL->getTypeSourceInfo();
10933 continue;
10934 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010935 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10936 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010937 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10938 return false;
10939 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010940 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010941 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010942
10943 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010944 if (!RD) return false;
10945 if (RD->isUnion()) return false;
10946 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10947 if (!CRD->isStandardLayout()) return false;
10948 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010949
Benjamin Kramer8c543672011-08-06 03:04:42 +000010950 // See if this is the last field decl in the record.
10951 const Decl *D = FD;
10952 while ((D = D->getNextDeclInContext()))
10953 if (isa<FieldDecl>(D))
10954 return false;
10955 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010956}
10957
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010958void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010959 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010960 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010961 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010962 if (IndexExpr->isValueDependent())
10963 return;
10964
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010965 const Type *EffectiveType =
10966 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010967 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010968 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010969 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010970 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010971 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010972
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010973 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010974 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010975 return;
Richard Smith13f67182011-12-16 19:31:14 +000010976 if (IndexNegated)
10977 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010978
Craig Topperc3ec1492014-05-26 06:22:03 +000010979 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010980 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10981 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010982 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010983 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010984
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010985 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010986 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010987 if (!size.isStrictlyPositive())
10988 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010989
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010990 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010991 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010992 // Make sure we're comparing apples to apples when comparing index to size
10993 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10994 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010995 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010996 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010997 if (ptrarith_typesize != array_typesize) {
10998 // There's a cast to a different size type involved
10999 uint64_t ratio = array_typesize / ptrarith_typesize;
11000 // TODO: Be smarter about handling cases where array_typesize is not a
11001 // multiple of ptrarith_typesize
11002 if (ptrarith_typesize * ratio == array_typesize)
11003 size *= llvm::APInt(size.getBitWidth(), ratio);
11004 }
11005 }
11006
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011007 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011008 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011009 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011010 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011011
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011012 // For array subscripting the index must be less than size, but for pointer
11013 // arithmetic also allow the index (offset) to be equal to size since
11014 // computing the next address after the end of the array is legal and
11015 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011016 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011017 return;
11018
11019 // Also don't warn for arrays of size 1 which are members of some
11020 // structure. These are often used to approximate flexible arrays in C89
11021 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011022 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011023 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011024
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011025 // Suppress the warning if the subscript expression (as identified by the
11026 // ']' location) and the index expression are both from macro expansions
11027 // within a system header.
11028 if (ASE) {
11029 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11030 ASE->getRBracketLoc());
11031 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11032 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11033 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011034 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011035 return;
11036 }
11037 }
11038
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011039 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011040 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011041 DiagID = diag::warn_array_index_exceeds_bounds;
11042
11043 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11044 PDiag(DiagID) << index.toString(10, true)
11045 << size.toString(10, true)
11046 << (unsigned)size.getLimitedValue(~0U)
11047 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011048 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011049 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011050 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011051 DiagID = diag::warn_ptr_arith_precedes_bounds;
11052 if (index.isNegative()) index = -index;
11053 }
11054
11055 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11056 PDiag(DiagID) << index.toString(10, true)
11057 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011058 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011059
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011060 if (!ND) {
11061 // Try harder to find a NamedDecl to point at in the note.
11062 while (const ArraySubscriptExpr *ASE =
11063 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11064 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11065 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11066 ND = dyn_cast<NamedDecl>(DRE->getDecl());
11067 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11068 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11069 }
11070
Chandler Carruth1af88f12011-02-17 21:10:52 +000011071 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011072 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11073 PDiag(diag::note_array_index_out_of_bounds)
11074 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011075}
11076
Ted Kremenekdf26df72011-03-01 18:41:00 +000011077void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011078 int AllowOnePastEnd = 0;
11079 while (expr) {
11080 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011081 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011082 case Stmt::ArraySubscriptExprClass: {
11083 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011084 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011085 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000011086 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011087 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011088 case Stmt::OMPArraySectionExprClass: {
11089 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11090 if (ASE->getLowerBound())
11091 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11092 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11093 return;
11094 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011095 case Stmt::UnaryOperatorClass: {
11096 // Only unwrap the * and & unary operators
11097 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11098 expr = UO->getSubExpr();
11099 switch (UO->getOpcode()) {
11100 case UO_AddrOf:
11101 AllowOnePastEnd++;
11102 break;
11103 case UO_Deref:
11104 AllowOnePastEnd--;
11105 break;
11106 default:
11107 return;
11108 }
11109 break;
11110 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011111 case Stmt::ConditionalOperatorClass: {
11112 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11113 if (const Expr *lhs = cond->getLHS())
11114 CheckArrayAccess(lhs);
11115 if (const Expr *rhs = cond->getRHS())
11116 CheckArrayAccess(rhs);
11117 return;
11118 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011119 case Stmt::CXXOperatorCallExprClass: {
11120 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11121 for (const auto *Arg : OCE->arguments())
11122 CheckArrayAccess(Arg);
11123 return;
11124 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011125 default:
11126 return;
11127 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011128 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011129}
John McCall31168b02011-06-15 23:02:42 +000011130
11131//===--- CHECK: Objective-C retain cycles ----------------------------------//
11132
11133namespace {
John McCall31168b02011-06-15 23:02:42 +000011134
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011135struct RetainCycleOwner {
11136 VarDecl *Variable = nullptr;
11137 SourceRange Range;
11138 SourceLocation Loc;
11139 bool Indirect = false;
11140
11141 RetainCycleOwner() = default;
11142
11143 void setLocsFrom(Expr *e) {
11144 Loc = e->getExprLoc();
11145 Range = e->getSourceRange();
11146 }
11147};
11148
11149} // namespace
John McCall31168b02011-06-15 23:02:42 +000011150
11151/// Consider whether capturing the given variable can possibly lead to
11152/// a retain cycle.
11153static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011154 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011155 // lifetime. In MRR, it's captured strongly if the variable is
11156 // __block and has an appropriate type.
11157 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11158 return false;
11159
11160 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011161 if (ref)
11162 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011163 return true;
11164}
11165
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011166static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011167 while (true) {
11168 e = e->IgnoreParens();
11169 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11170 switch (cast->getCastKind()) {
11171 case CK_BitCast:
11172 case CK_LValueBitCast:
11173 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011174 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011175 e = cast->getSubExpr();
11176 continue;
11177
John McCall31168b02011-06-15 23:02:42 +000011178 default:
11179 return false;
11180 }
11181 }
11182
11183 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11184 ObjCIvarDecl *ivar = ref->getDecl();
11185 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11186 return false;
11187
11188 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011189 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011190 return false;
11191
11192 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11193 owner.Indirect = true;
11194 return true;
11195 }
11196
11197 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11198 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11199 if (!var) return false;
11200 return considerVariable(var, ref, owner);
11201 }
11202
John McCall31168b02011-06-15 23:02:42 +000011203 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11204 if (member->isArrow()) return false;
11205
11206 // Don't count this as an indirect ownership.
11207 e = member->getBase();
11208 continue;
11209 }
11210
John McCallfe96e0b2011-11-06 09:01:30 +000011211 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11212 // Only pay attention to pseudo-objects on property references.
11213 ObjCPropertyRefExpr *pre
11214 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11215 ->IgnoreParens());
11216 if (!pre) return false;
11217 if (pre->isImplicitProperty()) return false;
11218 ObjCPropertyDecl *property = pre->getExplicitProperty();
11219 if (!property->isRetaining() &&
11220 !(property->getPropertyIvarDecl() &&
11221 property->getPropertyIvarDecl()->getType()
11222 .getObjCLifetime() == Qualifiers::OCL_Strong))
11223 return false;
11224
11225 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011226 if (pre->isSuperReceiver()) {
11227 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11228 if (!owner.Variable)
11229 return false;
11230 owner.Loc = pre->getLocation();
11231 owner.Range = pre->getSourceRange();
11232 return true;
11233 }
John McCallfe96e0b2011-11-06 09:01:30 +000011234 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11235 ->getSourceExpr());
11236 continue;
11237 }
11238
John McCall31168b02011-06-15 23:02:42 +000011239 // Array ivars?
11240
11241 return false;
11242 }
11243}
11244
11245namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011246
John McCall31168b02011-06-15 23:02:42 +000011247 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011248 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011249 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011250 Expr *Capturer = nullptr;
11251 bool VarWillBeReased = false;
11252
11253 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11254 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11255 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011256
11257 void VisitDeclRefExpr(DeclRefExpr *ref) {
11258 if (ref->getDecl() == Variable && !Capturer)
11259 Capturer = ref;
11260 }
11261
John McCall31168b02011-06-15 23:02:42 +000011262 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11263 if (Capturer) return;
11264 Visit(ref->getBase());
11265 if (Capturer && ref->isFreeIvar())
11266 Capturer = ref;
11267 }
11268
11269 void VisitBlockExpr(BlockExpr *block) {
11270 // Look inside nested blocks
11271 if (block->getBlockDecl()->capturesVariable(Variable))
11272 Visit(block->getBlockDecl()->getBody());
11273 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011274
11275 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11276 if (Capturer) return;
11277 if (OVE->getSourceExpr())
11278 Visit(OVE->getSourceExpr());
11279 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011280
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011281 void VisitBinaryOperator(BinaryOperator *BinOp) {
11282 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11283 return;
11284 Expr *LHS = BinOp->getLHS();
11285 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11286 if (DRE->getDecl() != Variable)
11287 return;
11288 if (Expr *RHS = BinOp->getRHS()) {
11289 RHS = RHS->IgnoreParenCasts();
11290 llvm::APSInt Value;
11291 VarWillBeReased =
11292 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11293 }
11294 }
11295 }
John McCall31168b02011-06-15 23:02:42 +000011296 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011297
11298} // namespace
John McCall31168b02011-06-15 23:02:42 +000011299
11300/// Check whether the given argument is a block which captures a
11301/// variable.
11302static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11303 assert(owner.Variable && owner.Loc.isValid());
11304
11305 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011306
11307 // Look through [^{...} copy] and Block_copy(^{...}).
11308 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11309 Selector Cmd = ME->getSelector();
11310 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11311 e = ME->getInstanceReceiver();
11312 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011313 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011314 e = e->IgnoreParenCasts();
11315 }
11316 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11317 if (CE->getNumArgs() == 1) {
11318 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011319 if (Fn) {
11320 const IdentifierInfo *FnI = Fn->getIdentifier();
11321 if (FnI && FnI->isStr("_Block_copy")) {
11322 e = CE->getArg(0)->IgnoreParenCasts();
11323 }
11324 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011325 }
11326 }
11327
John McCall31168b02011-06-15 23:02:42 +000011328 BlockExpr *block = dyn_cast<BlockExpr>(e);
11329 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011330 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011331
11332 FindCaptureVisitor visitor(S.Context, owner.Variable);
11333 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011334 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011335}
11336
11337static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11338 RetainCycleOwner &owner) {
11339 assert(capturer);
11340 assert(owner.Variable && owner.Loc.isValid());
11341
11342 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11343 << owner.Variable << capturer->getSourceRange();
11344 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11345 << owner.Indirect << owner.Range;
11346}
11347
11348/// Check for a keyword selector that starts with the word 'add' or
11349/// 'set'.
11350static bool isSetterLikeSelector(Selector sel) {
11351 if (sel.isUnarySelector()) return false;
11352
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011353 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011354 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011355 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011356 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011357 else if (str.startswith("add")) {
11358 // Specially whitelist 'addOperationWithBlock:'.
11359 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11360 return false;
11361 str = str.substr(3);
11362 }
John McCall31168b02011-06-15 23:02:42 +000011363 else
11364 return false;
11365
11366 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011367 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011368}
11369
Benjamin Kramer3a743452015-03-09 15:03:32 +000011370static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11371 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011372 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11373 Message->getReceiverInterface(),
11374 NSAPI::ClassId_NSMutableArray);
11375 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011376 return None;
11377 }
11378
11379 Selector Sel = Message->getSelector();
11380
11381 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11382 S.NSAPIObj->getNSArrayMethodKind(Sel);
11383 if (!MKOpt) {
11384 return None;
11385 }
11386
11387 NSAPI::NSArrayMethodKind MK = *MKOpt;
11388
11389 switch (MK) {
11390 case NSAPI::NSMutableArr_addObject:
11391 case NSAPI::NSMutableArr_insertObjectAtIndex:
11392 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11393 return 0;
11394 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11395 return 1;
11396
11397 default:
11398 return None;
11399 }
11400
11401 return None;
11402}
11403
11404static
11405Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11406 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011407 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11408 Message->getReceiverInterface(),
11409 NSAPI::ClassId_NSMutableDictionary);
11410 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011411 return None;
11412 }
11413
11414 Selector Sel = Message->getSelector();
11415
11416 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11417 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11418 if (!MKOpt) {
11419 return None;
11420 }
11421
11422 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11423
11424 switch (MK) {
11425 case NSAPI::NSMutableDict_setObjectForKey:
11426 case NSAPI::NSMutableDict_setValueForKey:
11427 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11428 return 0;
11429
11430 default:
11431 return None;
11432 }
11433
11434 return None;
11435}
11436
11437static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011438 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11439 Message->getReceiverInterface(),
11440 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011441
Alex Denisov5dfac812015-08-06 04:51:14 +000011442 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11443 Message->getReceiverInterface(),
11444 NSAPI::ClassId_NSMutableOrderedSet);
11445 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011446 return None;
11447 }
11448
11449 Selector Sel = Message->getSelector();
11450
11451 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11452 if (!MKOpt) {
11453 return None;
11454 }
11455
11456 NSAPI::NSSetMethodKind MK = *MKOpt;
11457
11458 switch (MK) {
11459 case NSAPI::NSMutableSet_addObject:
11460 case NSAPI::NSOrderedSet_setObjectAtIndex:
11461 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11462 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11463 return 0;
11464 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11465 return 1;
11466 }
11467
11468 return None;
11469}
11470
11471void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11472 if (!Message->isInstanceMessage()) {
11473 return;
11474 }
11475
11476 Optional<int> ArgOpt;
11477
11478 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11479 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11480 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11481 return;
11482 }
11483
11484 int ArgIndex = *ArgOpt;
11485
Alex Denisove1d882c2015-03-04 17:55:52 +000011486 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11487 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11488 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11489 }
11490
Alex Denisov5dfac812015-08-06 04:51:14 +000011491 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011492 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011493 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011494 Diag(Message->getSourceRange().getBegin(),
11495 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011496 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011497 }
11498 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011499 } else {
11500 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11501
11502 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11503 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11504 }
11505
11506 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11507 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11508 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11509 ValueDecl *Decl = ReceiverRE->getDecl();
11510 Diag(Message->getSourceRange().getBegin(),
11511 diag::warn_objc_circular_container)
11512 << Decl->getName() << Decl->getName();
11513 if (!ArgRE->isObjCSelfExpr()) {
11514 Diag(Decl->getLocation(),
11515 diag::note_objc_circular_container_declared_here)
11516 << Decl->getName();
11517 }
11518 }
11519 }
11520 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11521 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11522 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11523 ObjCIvarDecl *Decl = IvarRE->getDecl();
11524 Diag(Message->getSourceRange().getBegin(),
11525 diag::warn_objc_circular_container)
11526 << Decl->getName() << Decl->getName();
11527 Diag(Decl->getLocation(),
11528 diag::note_objc_circular_container_declared_here)
11529 << Decl->getName();
11530 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011531 }
11532 }
11533 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011534}
11535
John McCall31168b02011-06-15 23:02:42 +000011536/// Check a message send to see if it's likely to cause a retain cycle.
11537void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11538 // Only check instance methods whose selector looks like a setter.
11539 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11540 return;
11541
11542 // Try to find a variable that the receiver is strongly owned by.
11543 RetainCycleOwner owner;
11544 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011545 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011546 return;
11547 } else {
11548 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11549 owner.Variable = getCurMethodDecl()->getSelfDecl();
11550 owner.Loc = msg->getSuperLoc();
11551 owner.Range = msg->getSuperLoc();
11552 }
11553
11554 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000011555 const ObjCMethodDecl *MD = msg->getMethodDecl();
11556 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11557 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11558 // noescape blocks should not be retained by the method.
11559 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11560 continue;
John McCall31168b02011-06-15 23:02:42 +000011561 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000011562 }
11563 }
John McCall31168b02011-06-15 23:02:42 +000011564}
11565
11566/// Check a property assign to see if it's likely to cause a retain cycle.
11567void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11568 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011569 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011570 return;
11571
11572 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11573 diagnoseRetainCycle(*this, capturer, owner);
11574}
11575
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011576void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11577 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011578 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011579 return;
11580
11581 // Because we don't have an expression for the variable, we have to set the
11582 // location explicitly here.
11583 Owner.Loc = Var->getLocation();
11584 Owner.Range = Var->getSourceRange();
11585
11586 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11587 diagnoseRetainCycle(*this, Capturer, Owner);
11588}
11589
Ted Kremenek9304da92012-12-21 08:04:28 +000011590static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11591 Expr *RHS, bool isProperty) {
11592 // Check if RHS is an Objective-C object literal, which also can get
11593 // immediately zapped in a weak reference. Note that we explicitly
11594 // allow ObjCStringLiterals, since those are designed to never really die.
11595 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011596
Ted Kremenek64873352012-12-21 22:46:35 +000011597 // This enum needs to match with the 'select' in
11598 // warn_objc_arc_literal_assign (off-by-1).
11599 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11600 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11601 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011602
11603 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011604 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011605 << (isProperty ? 0 : 1)
11606 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011607
11608 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011609}
11610
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011611static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11612 Qualifiers::ObjCLifetime LT,
11613 Expr *RHS, bool isProperty) {
11614 // Strip off any implicit cast added to get to the one ARC-specific.
11615 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11616 if (cast->getCastKind() == CK_ARCConsumeObject) {
11617 S.Diag(Loc, diag::warn_arc_retained_assign)
11618 << (LT == Qualifiers::OCL_ExplicitNone)
11619 << (isProperty ? 0 : 1)
11620 << RHS->getSourceRange();
11621 return true;
11622 }
11623 RHS = cast->getSubExpr();
11624 }
11625
11626 if (LT == Qualifiers::OCL_Weak &&
11627 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11628 return true;
11629
11630 return false;
11631}
11632
Ted Kremenekb36234d2012-12-21 08:04:20 +000011633bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11634 QualType LHS, Expr *RHS) {
11635 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11636
11637 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11638 return false;
11639
11640 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11641 return true;
11642
11643 return false;
11644}
11645
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011646void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11647 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011648 QualType LHSType;
11649 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011650 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011651 ObjCPropertyRefExpr *PRE
11652 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11653 if (PRE && !PRE->isImplicitProperty()) {
11654 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11655 if (PD)
11656 LHSType = PD->getType();
11657 }
11658
11659 if (LHSType.isNull())
11660 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011661
11662 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11663
11664 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011665 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011666 getCurFunction()->markSafeWeakUse(LHS);
11667 }
11668
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011669 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11670 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011671
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011672 // FIXME. Check for other life times.
11673 if (LT != Qualifiers::OCL_None)
11674 return;
11675
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011676 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011677 if (PRE->isImplicitProperty())
11678 return;
11679 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11680 if (!PD)
11681 return;
11682
Bill Wendling44426052012-12-20 19:22:21 +000011683 unsigned Attributes = PD->getPropertyAttributes();
11684 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011685 // when 'assign' attribute was not explicitly specified
11686 // by user, ignore it and rely on property type itself
11687 // for lifetime info.
11688 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11689 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11690 LHSType->isObjCRetainableType())
11691 return;
11692
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011693 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011694 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011695 Diag(Loc, diag::warn_arc_retained_property_assign)
11696 << RHS->getSourceRange();
11697 return;
11698 }
11699 RHS = cast->getSubExpr();
11700 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011701 }
Bill Wendling44426052012-12-20 19:22:21 +000011702 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011703 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11704 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011705 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011706 }
11707}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011708
11709//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11710
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011711static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11712 SourceLocation StmtLoc,
11713 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011714 // Do not warn if the body is a macro that expands to nothing, e.g:
11715 //
11716 // #define CALL(x)
11717 // if (condition)
11718 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011719 if (Body->hasLeadingEmptyMacro())
11720 return false;
11721
11722 // Get line numbers of statement and body.
11723 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000011724 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011725 &StmtLineInvalid);
11726 if (StmtLineInvalid)
11727 return false;
11728
11729 bool BodyLineInvalid;
11730 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11731 &BodyLineInvalid);
11732 if (BodyLineInvalid)
11733 return false;
11734
11735 // Warn if null statement and body are on the same line.
11736 if (StmtLine != BodyLine)
11737 return false;
11738
11739 return true;
11740}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011741
11742void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11743 const Stmt *Body,
11744 unsigned DiagID) {
11745 // Since this is a syntactic check, don't emit diagnostic for template
11746 // instantiations, this just adds noise.
11747 if (CurrentInstantiationScope)
11748 return;
11749
11750 // The body should be a null statement.
11751 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11752 if (!NBody)
11753 return;
11754
11755 // Do the usual checks.
11756 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11757 return;
11758
11759 Diag(NBody->getSemiLoc(), DiagID);
11760 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11761}
11762
11763void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11764 const Stmt *PossibleBody) {
11765 assert(!CurrentInstantiationScope); // Ensured by caller
11766
11767 SourceLocation StmtLoc;
11768 const Stmt *Body;
11769 unsigned DiagID;
11770 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11771 StmtLoc = FS->getRParenLoc();
11772 Body = FS->getBody();
11773 DiagID = diag::warn_empty_for_body;
11774 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11775 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11776 Body = WS->getBody();
11777 DiagID = diag::warn_empty_while_body;
11778 } else
11779 return; // Neither `for' nor `while'.
11780
11781 // The body should be a null statement.
11782 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11783 if (!NBody)
11784 return;
11785
11786 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011787 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011788 return;
11789
11790 // Do the usual checks.
11791 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11792 return;
11793
11794 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11795 // noise level low, emit diagnostics only if for/while is followed by a
11796 // CompoundStmt, e.g.:
11797 // for (int i = 0; i < n; i++);
11798 // {
11799 // a(i);
11800 // }
11801 // or if for/while is followed by a statement with more indentation
11802 // than for/while itself:
11803 // for (int i = 0; i < n; i++);
11804 // a(i);
11805 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11806 if (!ProbableTypo) {
11807 bool BodyColInvalid;
11808 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11809 PossibleBody->getLocStart(),
11810 &BodyColInvalid);
11811 if (BodyColInvalid)
11812 return;
11813
11814 bool StmtColInvalid;
11815 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11816 S->getLocStart(),
11817 &StmtColInvalid);
11818 if (StmtColInvalid)
11819 return;
11820
11821 if (BodyCol > StmtCol)
11822 ProbableTypo = true;
11823 }
11824
11825 if (ProbableTypo) {
11826 Diag(NBody->getSemiLoc(), DiagID);
11827 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11828 }
11829}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011830
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011831//===--- CHECK: Warn on self move with std::move. -------------------------===//
11832
11833/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11834void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11835 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011836 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11837 return;
11838
Richard Smith51ec0cf2017-02-21 01:17:38 +000011839 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011840 return;
11841
11842 // Strip parens and casts away.
11843 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11844 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11845
11846 // Check for a call expression
11847 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11848 if (!CE || CE->getNumArgs() != 1)
11849 return;
11850
11851 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000011852 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011853 return;
11854
11855 // Get argument from std::move
11856 RHSExpr = CE->getArg(0);
11857
11858 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11859 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11860
11861 // Two DeclRefExpr's, check that the decls are the same.
11862 if (LHSDeclRef && RHSDeclRef) {
11863 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11864 return;
11865 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11866 RHSDeclRef->getDecl()->getCanonicalDecl())
11867 return;
11868
11869 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11870 << LHSExpr->getSourceRange()
11871 << RHSExpr->getSourceRange();
11872 return;
11873 }
11874
11875 // Member variables require a different approach to check for self moves.
11876 // MemberExpr's are the same if every nested MemberExpr refers to the same
11877 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11878 // the base Expr's are CXXThisExpr's.
11879 const Expr *LHSBase = LHSExpr;
11880 const Expr *RHSBase = RHSExpr;
11881 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11882 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11883 if (!LHSME || !RHSME)
11884 return;
11885
11886 while (LHSME && RHSME) {
11887 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11888 RHSME->getMemberDecl()->getCanonicalDecl())
11889 return;
11890
11891 LHSBase = LHSME->getBase();
11892 RHSBase = RHSME->getBase();
11893 LHSME = dyn_cast<MemberExpr>(LHSBase);
11894 RHSME = dyn_cast<MemberExpr>(RHSBase);
11895 }
11896
11897 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11898 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11899 if (LHSDeclRef && RHSDeclRef) {
11900 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11901 return;
11902 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11903 RHSDeclRef->getDecl()->getCanonicalDecl())
11904 return;
11905
11906 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11907 << LHSExpr->getSourceRange()
11908 << RHSExpr->getSourceRange();
11909 return;
11910 }
11911
11912 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11913 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11914 << LHSExpr->getSourceRange()
11915 << RHSExpr->getSourceRange();
11916}
11917
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011918//===--- Layout compatibility ----------------------------------------------//
11919
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011920static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011921
11922/// \brief Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011923static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011924 // C++11 [dcl.enum] p8:
11925 // Two enumeration types are layout-compatible if they have the same
11926 // underlying type.
11927 return ED1->isComplete() && ED2->isComplete() &&
11928 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11929}
11930
11931/// \brief Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011932static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
11933 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011934 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11935 return false;
11936
11937 if (Field1->isBitField() != Field2->isBitField())
11938 return false;
11939
11940 if (Field1->isBitField()) {
11941 // Make sure that the bit-fields are the same length.
11942 unsigned Bits1 = Field1->getBitWidthValue(C);
11943 unsigned Bits2 = Field2->getBitWidthValue(C);
11944
11945 if (Bits1 != Bits2)
11946 return false;
11947 }
11948
11949 return true;
11950}
11951
11952/// \brief Check if two standard-layout structs are layout-compatible.
11953/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011954static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
11955 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011956 // If both records are C++ classes, check that base classes match.
11957 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11958 // If one of records is a CXXRecordDecl we are in C++ mode,
11959 // thus the other one is a CXXRecordDecl, too.
11960 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11961 // Check number of base classes.
11962 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11963 return false;
11964
11965 // Check the base classes.
11966 for (CXXRecordDecl::base_class_const_iterator
11967 Base1 = D1CXX->bases_begin(),
11968 BaseEnd1 = D1CXX->bases_end(),
11969 Base2 = D2CXX->bases_begin();
11970 Base1 != BaseEnd1;
11971 ++Base1, ++Base2) {
11972 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11973 return false;
11974 }
11975 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11976 // If only RD2 is a C++ class, it should have zero base classes.
11977 if (D2CXX->getNumBases() > 0)
11978 return false;
11979 }
11980
11981 // Check the fields.
11982 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11983 Field2End = RD2->field_end(),
11984 Field1 = RD1->field_begin(),
11985 Field1End = RD1->field_end();
11986 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11987 if (!isLayoutCompatible(C, *Field1, *Field2))
11988 return false;
11989 }
11990 if (Field1 != Field1End || Field2 != Field2End)
11991 return false;
11992
11993 return true;
11994}
11995
11996/// \brief Check if two standard-layout unions are layout-compatible.
11997/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011998static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
11999 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012000 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012001 for (auto *Field2 : RD2->fields())
12002 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012003
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012004 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012005 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12006 I = UnmatchedFields.begin(),
12007 E = UnmatchedFields.end();
12008
12009 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012010 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012011 bool Result = UnmatchedFields.erase(*I);
12012 (void) Result;
12013 assert(Result);
12014 break;
12015 }
12016 }
12017 if (I == E)
12018 return false;
12019 }
12020
12021 return UnmatchedFields.empty();
12022}
12023
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012024static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12025 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012026 if (RD1->isUnion() != RD2->isUnion())
12027 return false;
12028
12029 if (RD1->isUnion())
12030 return isLayoutCompatibleUnion(C, RD1, RD2);
12031 else
12032 return isLayoutCompatibleStruct(C, RD1, RD2);
12033}
12034
12035/// \brief Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012036static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012037 if (T1.isNull() || T2.isNull())
12038 return false;
12039
12040 // C++11 [basic.types] p11:
12041 // If two types T1 and T2 are the same type, then T1 and T2 are
12042 // layout-compatible types.
12043 if (C.hasSameType(T1, T2))
12044 return true;
12045
12046 T1 = T1.getCanonicalType().getUnqualifiedType();
12047 T2 = T2.getCanonicalType().getUnqualifiedType();
12048
12049 const Type::TypeClass TC1 = T1->getTypeClass();
12050 const Type::TypeClass TC2 = T2->getTypeClass();
12051
12052 if (TC1 != TC2)
12053 return false;
12054
12055 if (TC1 == Type::Enum) {
12056 return isLayoutCompatible(C,
12057 cast<EnumType>(T1)->getDecl(),
12058 cast<EnumType>(T2)->getDecl());
12059 } else if (TC1 == Type::Record) {
12060 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12061 return false;
12062
12063 return isLayoutCompatible(C,
12064 cast<RecordType>(T1)->getDecl(),
12065 cast<RecordType>(T2)->getDecl());
12066 }
12067
12068 return false;
12069}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012070
12071//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12072
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012073/// \brief Given a type tag expression find the type tag itself.
12074///
12075/// \param TypeExpr Type tag expression, as it appears in user's code.
12076///
12077/// \param VD Declaration of an identifier that appears in a type tag.
12078///
12079/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012080static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12081 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012082 while(true) {
12083 if (!TypeExpr)
12084 return false;
12085
12086 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12087
12088 switch (TypeExpr->getStmtClass()) {
12089 case Stmt::UnaryOperatorClass: {
12090 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12091 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12092 TypeExpr = UO->getSubExpr();
12093 continue;
12094 }
12095 return false;
12096 }
12097
12098 case Stmt::DeclRefExprClass: {
12099 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12100 *VD = DRE->getDecl();
12101 return true;
12102 }
12103
12104 case Stmt::IntegerLiteralClass: {
12105 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12106 llvm::APInt MagicValueAPInt = IL->getValue();
12107 if (MagicValueAPInt.getActiveBits() <= 64) {
12108 *MagicValue = MagicValueAPInt.getZExtValue();
12109 return true;
12110 } else
12111 return false;
12112 }
12113
12114 case Stmt::BinaryConditionalOperatorClass:
12115 case Stmt::ConditionalOperatorClass: {
12116 const AbstractConditionalOperator *ACO =
12117 cast<AbstractConditionalOperator>(TypeExpr);
12118 bool Result;
12119 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12120 if (Result)
12121 TypeExpr = ACO->getTrueExpr();
12122 else
12123 TypeExpr = ACO->getFalseExpr();
12124 continue;
12125 }
12126 return false;
12127 }
12128
12129 case Stmt::BinaryOperatorClass: {
12130 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12131 if (BO->getOpcode() == BO_Comma) {
12132 TypeExpr = BO->getRHS();
12133 continue;
12134 }
12135 return false;
12136 }
12137
12138 default:
12139 return false;
12140 }
12141 }
12142}
12143
12144/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12145///
12146/// \param TypeExpr Expression that specifies a type tag.
12147///
12148/// \param MagicValues Registered magic values.
12149///
12150/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12151/// kind.
12152///
12153/// \param TypeInfo Information about the corresponding C type.
12154///
12155/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012156static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012157 const IdentifierInfo *ArgumentKind,
12158 const Expr *TypeExpr, const ASTContext &Ctx,
12159 const llvm::DenseMap<Sema::TypeTagMagicValue,
12160 Sema::TypeTagData> *MagicValues,
12161 bool &FoundWrongKind,
12162 Sema::TypeTagData &TypeInfo) {
12163 FoundWrongKind = false;
12164
12165 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012166 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012167
12168 uint64_t MagicValue;
12169
12170 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12171 return false;
12172
12173 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012174 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012175 if (I->getArgumentKind() != ArgumentKind) {
12176 FoundWrongKind = true;
12177 return false;
12178 }
12179 TypeInfo.Type = I->getMatchingCType();
12180 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12181 TypeInfo.MustBeNull = I->getMustBeNull();
12182 return true;
12183 }
12184 return false;
12185 }
12186
12187 if (!MagicValues)
12188 return false;
12189
12190 llvm::DenseMap<Sema::TypeTagMagicValue,
12191 Sema::TypeTagData>::const_iterator I =
12192 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12193 if (I == MagicValues->end())
12194 return false;
12195
12196 TypeInfo = I->second;
12197 return true;
12198}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012199
12200void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12201 uint64_t MagicValue, QualType Type,
12202 bool LayoutCompatible,
12203 bool MustBeNull) {
12204 if (!TypeTagForDatatypeMagicValues)
12205 TypeTagForDatatypeMagicValues.reset(
12206 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12207
12208 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12209 (*TypeTagForDatatypeMagicValues)[Magic] =
12210 TypeTagData(Type, LayoutCompatible, MustBeNull);
12211}
12212
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012213static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012214 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12215 if (!BT1)
12216 return false;
12217
12218 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12219 if (!BT2)
12220 return false;
12221
12222 BuiltinType::Kind T1Kind = BT1->getKind();
12223 BuiltinType::Kind T2Kind = BT2->getKind();
12224
12225 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12226 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12227 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12228 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12229}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012230
12231void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012232 const ArrayRef<const Expr *> ExprArgs,
12233 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012234 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12235 bool IsPointerAttr = Attr->getIsPointer();
12236
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012237 // Retrieve the argument representing the 'type_tag'.
12238 if (Attr->getTypeTagIdx() >= ExprArgs.size()) {
12239 // Add 1 to display the user's specified value.
12240 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12241 << 0 << Attr->getTypeTagIdx() + 1;
12242 return;
12243 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012244 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12245 bool FoundWrongKind;
12246 TypeTagData TypeInfo;
12247 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12248 TypeTagForDatatypeMagicValues.get(),
12249 FoundWrongKind, TypeInfo)) {
12250 if (FoundWrongKind)
12251 Diag(TypeTagExpr->getExprLoc(),
12252 diag::warn_type_tag_for_datatype_wrong_kind)
12253 << TypeTagExpr->getSourceRange();
12254 return;
12255 }
12256
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012257 // Retrieve the argument representing the 'arg_idx'.
12258 if (Attr->getArgumentIdx() >= ExprArgs.size()) {
12259 // Add 1 to display the user's specified value.
12260 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12261 << 1 << Attr->getArgumentIdx() + 1;
12262 return;
12263 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012264 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12265 if (IsPointerAttr) {
12266 // Skip implicit cast of pointer to `void *' (as a function argument).
12267 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012268 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012269 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012270 ArgumentExpr = ICE->getSubExpr();
12271 }
12272 QualType ArgumentType = ArgumentExpr->getType();
12273
12274 // Passing a `void*' pointer shouldn't trigger a warning.
12275 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12276 return;
12277
12278 if (TypeInfo.MustBeNull) {
12279 // Type tag with matching void type requires a null pointer.
12280 if (!ArgumentExpr->isNullPointerConstant(Context,
12281 Expr::NPC_ValueDependentIsNotNull)) {
12282 Diag(ArgumentExpr->getExprLoc(),
12283 diag::warn_type_safety_null_pointer_required)
12284 << ArgumentKind->getName()
12285 << ArgumentExpr->getSourceRange()
12286 << TypeTagExpr->getSourceRange();
12287 }
12288 return;
12289 }
12290
12291 QualType RequiredType = TypeInfo.Type;
12292 if (IsPointerAttr)
12293 RequiredType = Context.getPointerType(RequiredType);
12294
12295 bool mismatch = false;
12296 if (!TypeInfo.LayoutCompatible) {
12297 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12298
12299 // C++11 [basic.fundamental] p1:
12300 // Plain char, signed char, and unsigned char are three distinct types.
12301 //
12302 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12303 // char' depending on the current char signedness mode.
12304 if (mismatch)
12305 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12306 RequiredType->getPointeeType())) ||
12307 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12308 mismatch = false;
12309 } else
12310 if (IsPointerAttr)
12311 mismatch = !isLayoutCompatible(Context,
12312 ArgumentType->getPointeeType(),
12313 RequiredType->getPointeeType());
12314 else
12315 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12316
12317 if (mismatch)
12318 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012319 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012320 << TypeInfo.LayoutCompatible << RequiredType
12321 << ArgumentExpr->getSourceRange()
12322 << TypeTagExpr->getSourceRange();
12323}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012324
12325void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12326 CharUnits Alignment) {
12327 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12328}
12329
12330void Sema::DiagnoseMisalignedMembers() {
12331 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012332 const NamedDecl *ND = m.RD;
12333 if (ND->getName().empty()) {
12334 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12335 ND = TD;
12336 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012337 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012338 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012339 }
12340 MisalignedMembers.clear();
12341}
12342
12343void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012344 E = E->IgnoreParens();
12345 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012346 return;
12347 if (isa<UnaryOperator>(E) &&
12348 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12349 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12350 if (isa<MemberExpr>(Op)) {
12351 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12352 MisalignedMember(Op));
12353 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012354 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012355 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12356 Context.getTypeAlignInChars(
12357 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012358 MisalignedMembers.erase(MA);
12359 }
12360 }
12361}
12362
12363void Sema::RefersToMemberWithReducedAlignment(
12364 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012365 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12366 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012367 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012368 if (!ME)
12369 return;
12370
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012371 // No need to check expressions with an __unaligned-qualified type.
12372 if (E->getType().getQualifiers().hasUnaligned())
12373 return;
12374
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012375 // For a chain of MemberExpr like "a.b.c.d" this list
12376 // will keep FieldDecl's like [d, c, b].
12377 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12378 const MemberExpr *TopME = nullptr;
12379 bool AnyIsPacked = false;
12380 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012381 QualType BaseType = ME->getBase()->getType();
12382 if (ME->isArrow())
12383 BaseType = BaseType->getPointeeType();
12384 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012385 if (RD->isInvalidDecl())
12386 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012387
12388 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012389 auto *FD = dyn_cast<FieldDecl>(MD);
12390 // We do not care about non-data members.
12391 if (!FD || FD->isInvalidDecl())
12392 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012393
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012394 AnyIsPacked =
12395 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12396 ReverseMemberChain.push_back(FD);
12397
12398 TopME = ME;
12399 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12400 } while (ME);
12401 assert(TopME && "We did not compute a topmost MemberExpr!");
12402
12403 // Not the scope of this diagnostic.
12404 if (!AnyIsPacked)
12405 return;
12406
12407 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12408 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12409 // TODO: The innermost base of the member expression may be too complicated.
12410 // For now, just disregard these cases. This is left for future
12411 // improvement.
12412 if (!DRE && !isa<CXXThisExpr>(TopBase))
12413 return;
12414
12415 // Alignment expected by the whole expression.
12416 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12417
12418 // No need to do anything else with this case.
12419 if (ExpectedAlignment.isOne())
12420 return;
12421
12422 // Synthesize offset of the whole access.
12423 CharUnits Offset;
12424 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12425 I++) {
12426 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12427 }
12428
12429 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12430 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12431 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12432
12433 // The base expression of the innermost MemberExpr may give
12434 // stronger guarantees than the class containing the member.
12435 if (DRE && !TopME->isArrow()) {
12436 const ValueDecl *VD = DRE->getDecl();
12437 if (!VD->getType()->isReferenceType())
12438 CompleteObjectAlignment =
12439 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12440 }
12441
12442 // Check if the synthesized offset fulfills the alignment.
12443 if (Offset % ExpectedAlignment != 0 ||
12444 // It may fulfill the offset it but the effective alignment may still be
12445 // lower than the expected expression alignment.
12446 CompleteObjectAlignment < ExpectedAlignment) {
12447 // If this happens, we want to determine a sensible culprit of this.
12448 // Intuitively, watching the chain of member expressions from right to
12449 // left, we start with the required alignment (as required by the field
12450 // type) but some packed attribute in that chain has reduced the alignment.
12451 // It may happen that another packed structure increases it again. But if
12452 // we are here such increase has not been enough. So pointing the first
12453 // FieldDecl that either is packed or else its RecordDecl is,
12454 // seems reasonable.
12455 FieldDecl *FD = nullptr;
12456 CharUnits Alignment;
12457 for (FieldDecl *FDI : ReverseMemberChain) {
12458 if (FDI->hasAttr<PackedAttr>() ||
12459 FDI->getParent()->hasAttr<PackedAttr>()) {
12460 FD = FDI;
12461 Alignment = std::min(
12462 Context.getTypeAlignInChars(FD->getType()),
12463 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12464 break;
12465 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012466 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012467 assert(FD && "We did not find a packed FieldDecl!");
12468 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012469 }
12470}
12471
12472void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12473 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012474
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012475 RefersToMemberWithReducedAlignment(
12476 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12477 _2, _3, _4));
12478}