clang  6.0.0
SemaChecking.cpp
Go to the documentation of this file.
1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements extra semantic analysis beyond what is enforced
11 // by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.h"
30 #include "clang/AST/NSAPI.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"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/LLVM.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
63 #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"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #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"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #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>
97 
98 using namespace clang;
99 using namespace sema;
100 
102  unsigned ByteNo) const {
103  return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104  Context.getTargetInfo());
105 }
106 
107 /// 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.
109 static 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 
127 /// Check that the first argument to __builtin_annotation is an integer
128 /// and the second argument is a non-wide string literal.
129 static 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();
139  return true;
140  }
141 
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);
152  return false;
153 }
154 
155 static 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 
177 /// Check that the argument to __builtin_addressof is a glvalue, and set the
178 /// result type to the corresponding pointer type.
179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180  if (checkArgCount(S, TheCall, 1))
181  return true;
182 
183  ExprResult Arg(TheCall->getArg(0));
184  QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
185  if (ResultType.isNull())
186  return true;
187 
188  TheCall->setArg(0, Arg.get());
189  TheCall->setType(ResultType);
190  return false;
191 }
192 
193 static 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 
226 static 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 
254 static 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 
299  QualType ReturnTy = CE->getCallReturnType(S.Context);
300  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 
317 static 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.
323  if (SemaRef.inTemplateInstantiation())
324  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 
339 static 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.
345 static 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() !=
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 
378 static 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 
387 static 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);
396  if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
397  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 
413 /// 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.
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(),
423  diag::err_opencl_builtin_expected_type)
424  << TheCall->getDirectCallee() << "block";
425  return true;
426  }
427  return checkOpenCLBlockArgs(S, BlockArg);
428 }
429 
430 /// Diagnose integer type and any valid implicit conversion to it.
431 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432  const QualType &IntType);
433 
435  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 }
442 
443 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444 /// 'local void*' parameter of passed block.
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, ...)
493 static 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(),
509  diag::err_opencl_builtin_expected_type)
510  << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
511  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(),
517  diag::err_opencl_builtin_expected_type)
518  << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
519  return true;
520  }
521 
522  // Third argument is always an ndrange_t type.
523  if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
524  S.Diag(TheCall->getArg(2)->getLocStart(),
525  diag::err_opencl_builtin_expected_type)
526  << TheCall->getDirectCallee() << "'ndrange_t'";
527  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)) {
535  S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536  << TheCall->getDirectCallee() << "block";
537  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)) {
558  S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559  << TheCall->getDirectCallee() << "block";
560  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(),
568  diag::err_opencl_builtin_expected_type)
569  << TheCall->getDirectCallee() << "integer";
570  return true;
571  }
572  // check remaining common arguments.
573  Expr *Arg4 = TheCall->getArg(4);
574  Expr *Arg5 = TheCall->getArg(5);
575 
576  // Fifth argument is always passed as a pointer to clk_event_t.
577  if (!Arg4->isNullPointerConstant(S.Context,
580  S.Diag(TheCall->getArg(4)->getLocStart(),
581  diag::err_opencl_builtin_expected_type)
582  << TheCall->getDirectCallee()
584  return true;
585  }
586 
587  // Sixth argument is always passed as a pointer to clk_event_t.
588  if (!Arg5->isNullPointerConstant(S.Context,
590  !(Arg5->getType()->isPointerType() &&
591  Arg5->getType()->getPointeeType()->isClkEventT())) {
592  S.Diag(TheCall->getArg(5)->getLocStart(),
593  diag::err_opencl_builtin_expected_type)
594  << TheCall->getDirectCallee()
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 
611 /// Returns OpenCL access qual.
612 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
613  return D->getAttr<OpenCLAccessAttr>();
614 }
615 
616 /// Returns true if pipe element type is different from the pointer.
617 static 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)
622  << Call->getDirectCallee() << Arg0->getSourceRange();
623  return true;
624  }
625  OpenCLAccessAttr *AccessQual =
626  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.
631  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;
662  }
663  return false;
664 }
665 
666 /// Returns true if pipe element type is different from the pointer.
667 static 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());
671  const QualType EltTy = PipeTy->getElementType();
672  const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
673  // 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.
675  if (!ArgTy ||
676  !S.Context.hasSameType(
677  EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
678  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
679  << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
680  << ArgIdx->getType() << ArgIdx->getSourceRange();
681  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.
690 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
691  // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692  // functions have two forms.
693  switch (Call->getNumArgs()) {
694  case 2:
695  if (checkOpenCLPipeArg(S, Call))
696  return true;
697  // The call with 2 arguments should be
698  // read/write_pipe(pipe T, T*).
699  // Check packet type T.
700  if (checkOpenCLPipePacketType(S, Call, 1))
701  return true;
702  break;
703 
704  case 4: {
705  if (checkOpenCLPipeArg(S, Call))
706  return true;
707  // The call with 4 arguments should be
708  // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709  // Check reserve_id_t.
710  if (!Call->getArg(1)->getType()->isReserveIDT()) {
711  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
712  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
713  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
714  return true;
715  }
716 
717  // Check the index.
718  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)
722  << Call->getDirectCallee() << S.Context.UnsignedIntTy
723  << Arg2->getType() << Arg2->getSourceRange();
724  return true;
725  }
726 
727  // Check packet type T.
728  if (checkOpenCLPipePacketType(S, Call, 3))
729  return true;
730  } break;
731  default:
732  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
733  << Call->getDirectCallee() << Call->getSourceRange();
734  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.
745 static 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 
752  // Check the reserve size.
753  if (!Call->getArg(1)->getType()->isIntegerType() &&
754  !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
756  << Call->getDirectCallee() << S.Context.UnsignedIntTy
757  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
758  return true;
759  }
760 
761  // 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 
766  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.
774 static 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 
781  // Check reserve_id_t.
782  if (!Call->getArg(1)->getType()->isReserveIDT()) {
783  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
784  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
785  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
786  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.
797 static 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)
803  << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
804  return true;
805  }
806 
807  return false;
808 }
809 
810 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
811 // \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.
816 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
817  CallExpr *Call) {
818  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;
841  case Builtin::BIto_private:
842  Qual.setAddressSpace(LangAS::opencl_private);
843  break;
844  default:
845  llvm_unreachable("Invalid builtin function");
846  }
848  RT.getUnqualifiedType(), Qual)));
849 
850  return false;
851 }
852 
854 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
855  CallExpr *TheCall) {
856  ExprResult TheCallResult(TheCall);
857 
858  // Find out if any arguments are required to be integer constant expressions.
859  unsigned ICEArguments = 0;
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 
876  switch (BuiltinID) {
877  case Builtin::BI__builtin___CFStringMakeConstantString:
878  assert(TheCall->getNumArgs() == 1 &&
879  "Wrong # arguments to builtin CFStringMakeConstantString");
880  if (CheckObjCString(TheCall->getArg(0)))
881  return ExprError();
882  break;
883  case Builtin::BI__builtin_ms_va_start:
884  case Builtin::BI__builtin_stdarg_start:
885  case Builtin::BI__builtin_va_start:
886  if (SemaBuiltinVAStart(BuiltinID, TheCall))
887  return ExprError();
888  break;
889  case Builtin::BI__va_start: {
890  switch (Context.getTargetInfo().getTriple().getArch()) {
891  case llvm::Triple::arm:
892  case llvm::Triple::thumb:
893  if (SemaBuiltinVAStartARMMicrosoft(TheCall))
894  return ExprError();
895  break;
896  default:
897  if (SemaBuiltinVAStart(BuiltinID, TheCall))
898  return ExprError();
899  break;
900  }
901  break;
902  }
903  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:
909  if (SemaBuiltinUnorderedCompare(TheCall))
910  return ExprError();
911  break;
912  case Builtin::BI__builtin_fpclassify:
913  if (SemaBuiltinFPClassification(TheCall, 6))
914  return ExprError();
915  break;
916  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:
921  if (SemaBuiltinFPClassification(TheCall, 1))
922  return ExprError();
923  break;
924  case Builtin::BI__builtin_shufflevector:
925  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.
928  case Builtin::BI__builtin_prefetch:
929  if (SemaBuiltinPrefetch(TheCall))
930  return ExprError();
931  break;
932  case Builtin::BI__builtin_alloca_with_align:
933  if (SemaBuiltinAllocaWithAlign(TheCall))
934  return ExprError();
935  break;
936  case Builtin::BI__assume:
937  case Builtin::BI__builtin_assume:
938  if (SemaBuiltinAssume(TheCall))
939  return ExprError();
940  break;
941  case Builtin::BI__builtin_assume_aligned:
942  if (SemaBuiltinAssumeAligned(TheCall))
943  return ExprError();
944  break;
945  case Builtin::BI__builtin_object_size:
946  if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
947  return ExprError();
948  break;
949  case Builtin::BI__builtin_longjmp:
950  if (SemaBuiltinLongjmp(TheCall))
951  return ExprError();
952  break;
953  case Builtin::BI__builtin_setjmp:
954  if (SemaBuiltinSetjmp(TheCall))
955  return ExprError();
956  break;
957  case Builtin::BI_setjmp:
958  case Builtin::BI_setjmpex:
959  if (checkArgCount(*this, TheCall, 1))
960  return true;
961  break;
962  case Builtin::BI__builtin_classify_type:
963  if (checkArgCount(*this, TheCall, 1)) return true;
964  TheCall->setType(Context.IntTy);
965  break;
966  case Builtin::BI__builtin_constant_p:
967  if (checkArgCount(*this, TheCall, 1)) return true;
968  TheCall->setType(Context.IntTy);
969  break;
970  case Builtin::BI__sync_fetch_and_add:
971  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:
976  case Builtin::BI__sync_fetch_and_sub:
977  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:
982  case Builtin::BI__sync_fetch_and_or:
983  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:
988  case Builtin::BI__sync_fetch_and_and:
989  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:
994  case Builtin::BI__sync_fetch_and_xor:
995  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:
1000  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:
1006  case Builtin::BI__sync_add_and_fetch:
1007  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:
1012  case Builtin::BI__sync_sub_and_fetch:
1013  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:
1018  case Builtin::BI__sync_and_and_fetch:
1019  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:
1024  case Builtin::BI__sync_or_and_fetch:
1025  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:
1030  case Builtin::BI__sync_xor_and_fetch:
1031  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:
1036  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:
1042  case Builtin::BI__sync_val_compare_and_swap:
1043  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:
1048  case Builtin::BI__sync_bool_compare_and_swap:
1049  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:
1054  case Builtin::BI__sync_lock_test_and_set:
1055  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:
1060  case Builtin::BI__sync_lock_release:
1061  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:
1066  case Builtin::BI__sync_swap:
1067  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:
1072  return SemaBuiltinAtomicOverloaded(TheCallResult);
1073  case Builtin::BI__builtin_nontemporal_load:
1074  case Builtin::BI__builtin_nontemporal_store:
1075  return SemaBuiltinNontemporalOverloaded(TheCallResult);
1076 #define BUILTIN(ID, TYPE, ATTRS)
1077 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078  case Builtin::BI##ID: \
1079  return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1080 #include "clang/Basic/Builtins.def"
1081  case Builtin::BI__annotation:
1082  if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1083  return ExprError();
1084  break;
1085  case Builtin::BI__builtin_annotation:
1086  if (SemaBuiltinAnnotation(*this, TheCall))
1087  return ExprError();
1088  break;
1089  case Builtin::BI__builtin_addressof:
1090  if (SemaBuiltinAddressof(*this, TheCall))
1091  return ExprError();
1092  break;
1093  case Builtin::BI__builtin_add_overflow:
1094  case Builtin::BI__builtin_sub_overflow:
1095  case Builtin::BI__builtin_mul_overflow:
1096  if (SemaBuiltinOverflow(*this, TheCall))
1097  return ExprError();
1098  break;
1099  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;
1113 
1114  // check secure string manipulation functions where overflows
1115  // are detectable at compile time
1116  case Builtin::BI__builtin___memcpy_chk:
1117  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;
1126  case Builtin::BI__builtin___memccpy_chk:
1127  SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1128  break;
1129  case Builtin::BI__builtin___snprintf_chk:
1130  case Builtin::BI__builtin___vsnprintf_chk:
1131  SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1132  break;
1133  case Builtin::BI__builtin_call_with_static_chain:
1134  if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1135  return ExprError();
1136  break;
1137  case Builtin::BI__exception_code:
1138  case Builtin::BI_exception_code:
1139  if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1140  diag::err_seh___except_block))
1141  return ExprError();
1142  break;
1143  case Builtin::BI__exception_info:
1144  case Builtin::BI_exception_info:
1145  if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1146  diag::err_seh___except_filter))
1147  return ExprError();
1148  break;
1149  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;
1161  // OpenCL v2.0, s6.13.16 - Pipe functions
1162  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();
1168  TheCall->setType(Context.IntTy);
1169  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:
1174  if (SemaBuiltinReserveRWPipe(*this, TheCall))
1175  return ExprError();
1176  break;
1177  case Builtin::BIsub_group_reserve_read_pipe:
1178  case Builtin::BIsub_group_reserve_write_pipe:
1179  if (checkOpenCLSubgroupExt(*this, TheCall) ||
1180  SemaBuiltinReserveRWPipe(*this, TheCall))
1181  return ExprError();
1182  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:
1187  if (SemaBuiltinCommitRWPipe(*this, TheCall))
1188  return ExprError();
1189  break;
1190  case Builtin::BIsub_group_commit_read_pipe:
1191  case Builtin::BIsub_group_commit_write_pipe:
1192  if (checkOpenCLSubgroupExt(*this, TheCall) ||
1193  SemaBuiltinCommitRWPipe(*this, TheCall))
1194  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();
1200  TheCall->setType(Context.UnsignedIntTy);
1201  break;
1202  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;
1208  // 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();
1217  break;
1218  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;
1224  case Builtin::BI__builtin_os_log_format:
1225  case Builtin::BI__builtin_os_log_format_buffer_size:
1226  if (SemaBuiltinOSLogFormat(TheCall))
1227  return ExprError();
1228  break;
1229  }
1230 
1231  // Since the target specific builtins for each arch overlap, only check those
1232  // of the arch we are compiling for.
1233  if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1234  switch (Context.getTargetInfo().getTriple().getArch()) {
1235  case llvm::Triple::arm:
1236  case llvm::Triple::armeb:
1237  case llvm::Triple::thumb:
1238  case llvm::Triple::thumbeb:
1239  if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1240  return ExprError();
1241  break;
1242  case llvm::Triple::aarch64:
1243  case llvm::Triple::aarch64_be:
1244  if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1245  return ExprError();
1246  break;
1247  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;
1254  case llvm::Triple::systemz:
1255  if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1256  return ExprError();
1257  break;
1258  case llvm::Triple::x86:
1259  case llvm::Triple::x86_64:
1260  if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1261  return ExprError();
1262  break;
1263  case llvm::Triple::ppc:
1264  case llvm::Triple::ppc64:
1265  case llvm::Triple::ppc64le:
1266  if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1267  return ExprError();
1268  break;
1269  default:
1270  break;
1271  }
1272  }
1273 
1274  return TheCallResult;
1275 }
1276 
1277 // Get the valid immediate range for the specified NEON type code.
1278 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1279  NeonTypeFlags Type(t);
1280  int IsQuad = ForceQuad ? true : Type.isQuad();
1281  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:
1291  case NeonTypeFlags::Poly64:
1292  return shift ? 63 : (1 << IsQuad) - 1;
1294  return shift ? 127 : (1 << IsQuad) - 1;
1296  assert(!shift && "cannot shift float types!");
1297  return (4 << IsQuad) - 1;
1299  assert(!shift && "cannot shift float types!");
1300  return (2 << IsQuad) - 1;
1302  assert(!shift && "cannot shift float types!");
1303  return (1 << IsQuad) - 1;
1304  }
1305  llvm_unreachable("Invalid NeonTypeFlag!");
1306 }
1307 
1308 /// 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.
1312  bool IsPolyUnsigned, bool IsInt64Long) {
1313  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:
1321  if (IsInt64Long)
1322  return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1323  else
1324  return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1325  : Context.LongLongTy;
1326  case NeonTypeFlags::Poly8:
1327  return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1328  case NeonTypeFlags::Poly16:
1329  return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1330  case NeonTypeFlags::Poly64:
1331  if (IsInt64Long)
1332  return Context.UnsignedLongTy;
1333  else
1334  return Context.UnsignedLongLongTy;
1336  break;
1338  return Context.HalfTy;
1340  return Context.FloatTy;
1342  return Context.DoubleTy;
1343  }
1344  llvm_unreachable("Invalid NeonTypeFlag!");
1345 }
1346 
1347 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1348  llvm::APSInt Result;
1349  uint64_t mask = 0;
1350  unsigned TV = 0;
1351  int PtrArgNum = -1;
1352  bool HasConstPtr = false;
1353  switch (BuiltinID) {
1354 #define GET_NEON_OVERLOAD_CHECK
1355 #include "clang/Basic/arm_neon.inc"
1356 #undef GET_NEON_OVERLOAD_CHECK
1357  }
1358 
1359  // For NEON intrinsics which are overloaded on vector element type, validate
1360  // the immediate which specifies which variant to emit.
1361  unsigned ImmArg = TheCall->getNumArgs()-1;
1362  if (mask) {
1363  if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1364  return true;
1365 
1366  TV = Result.getLimitedValue(64);
1367  if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1368  return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1369  << TheCall->getArg(ImmArg)->getSourceRange();
1370  }
1371 
1372  if (PtrArgNum >= 0) {
1373  // Check that pointer arguments have the specified type.
1374  Expr *Arg = TheCall->getArg(PtrArgNum);
1375  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1376  Arg = ICE->getSubExpr();
1377  ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1378  QualType RHSTy = RHS.get()->getType();
1379 
1380  llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1381  bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1382  Arch == llvm::Triple::aarch64_be;
1383  bool IsInt64Long =
1385  QualType EltTy =
1386  getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1387  if (HasConstPtr)
1388  EltTy = EltTy.withConst();
1389  QualType LHSTy = Context.getPointerType(EltTy);
1390  AssignConvertType ConvTy;
1391  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1392  if (RHS.isInvalid())
1393  return true;
1394  if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1395  RHS.get(), AA_Assigning))
1396  return true;
1397  }
1398 
1399  // For NEON intrinsics which take an immediate value as part of the
1400  // instruction, range check them here.
1401  unsigned i = 0, l = 0, u = 0;
1402  switch (BuiltinID) {
1403  default:
1404  return false;
1405 #define GET_NEON_IMMEDIATE_CHECK
1406 #include "clang/Basic/arm_neon.inc"
1407 #undef GET_NEON_IMMEDIATE_CHECK
1408  }
1409 
1410  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1411 }
1412 
1413 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1414  unsigned MaxWidth) {
1415  assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1416  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1417  BuiltinID == ARM::BI__builtin_arm_strex ||
1418  BuiltinID == ARM::BI__builtin_arm_stlex ||
1419  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1420  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1421  BuiltinID == AArch64::BI__builtin_arm_strex ||
1422  BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1423  "unexpected ARM builtin");
1424  bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1425  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1426  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1427  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1428 
1429  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1430 
1431  // Ensure that we have the proper number of arguments.
1432  if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1433  return true;
1434 
1435  // Inspect the pointer argument of the atomic builtin. This should always be
1436  // a pointer type, whose element is an integral scalar or pointer type.
1437  // Because it is a pointer type, we don't have to worry about any implicit
1438  // casts here.
1439  Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1440  ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1441  if (PointerArgRes.isInvalid())
1442  return true;
1443  PointerArg = PointerArgRes.get();
1444 
1445  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1446  if (!pointerType) {
1447  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1448  << PointerArg->getType() << PointerArg->getSourceRange();
1449  return true;
1450  }
1451 
1452  // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1453  // task is to insert the appropriate casts into the AST. First work out just
1454  // what the appropriate type is.
1455  QualType ValType = pointerType->getPointeeType();
1456  QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1457  if (IsLdrex)
1458  AddrType.addConst();
1459 
1460  // Issue a warning if the cast is dodgy.
1461  CastKind CastNeeded = CK_NoOp;
1462  if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1463  CastNeeded = CK_BitCast;
1464  Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1465  << PointerArg->getType()
1466  << Context.getPointerType(AddrType)
1467  << AA_Passing << PointerArg->getSourceRange();
1468  }
1469 
1470  // Finally, do the cast and replace the argument with the corrected version.
1471  AddrType = Context.getPointerType(AddrType);
1472  PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1473  if (PointerArgRes.isInvalid())
1474  return true;
1475  PointerArg = PointerArgRes.get();
1476 
1477  TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1478 
1479  // In general, we allow ints, floats and pointers to be loaded and stored.
1480  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1481  !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1482  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1483  << PointerArg->getType() << PointerArg->getSourceRange();
1484  return true;
1485  }
1486 
1487  // But ARM doesn't have instructions to deal with 128-bit versions.
1488  if (Context.getTypeSize(ValType) > MaxWidth) {
1489  assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1490  Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1491  << PointerArg->getType() << PointerArg->getSourceRange();
1492  return true;
1493  }
1494 
1495  switch (ValType.getObjCLifetime()) {
1496  case Qualifiers::OCL_None:
1498  // okay
1499  break;
1500 
1501  case Qualifiers::OCL_Weak:
1504  Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1505  << ValType << PointerArg->getSourceRange();
1506  return true;
1507  }
1508 
1509  if (IsLdrex) {
1510  TheCall->setType(ValType);
1511  return false;
1512  }
1513 
1514  // Initialize the argument to be stored.
1515  ExprResult ValArg = TheCall->getArg(0);
1517  Context, ValType, /*consume*/ false);
1518  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1519  if (ValArg.isInvalid())
1520  return true;
1521  TheCall->setArg(0, ValArg.get());
1522 
1523  // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1524  // but the custom checker bypasses all default analysis.
1525  TheCall->setType(Context.IntTy);
1526  return false;
1527 }
1528 
1529 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1530  if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1531  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1532  BuiltinID == ARM::BI__builtin_arm_strex ||
1533  BuiltinID == ARM::BI__builtin_arm_stlex) {
1534  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1535  }
1536 
1537  if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1538  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1539  SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1540  }
1541 
1542  if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1543  BuiltinID == ARM::BI__builtin_arm_wsr64)
1544  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1545 
1546  if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1547  BuiltinID == ARM::BI__builtin_arm_rsrp ||
1548  BuiltinID == ARM::BI__builtin_arm_wsr ||
1549  BuiltinID == ARM::BI__builtin_arm_wsrp)
1550  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1551 
1552  if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1553  return true;
1554 
1555  // For intrinsics which take an immediate value as part of the instruction,
1556  // range check them here.
1557  // FIXME: VFP Intrinsics should error if VFP not present.
1558  switch (BuiltinID) {
1559  default: return false;
1560  case ARM::BI__builtin_arm_ssat:
1561  return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1562  case ARM::BI__builtin_arm_usat:
1563  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1564  case ARM::BI__builtin_arm_ssat16:
1565  return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1566  case ARM::BI__builtin_arm_usat16:
1567  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1568  case ARM::BI__builtin_arm_vcvtr_f:
1569  case ARM::BI__builtin_arm_vcvtr_d:
1570  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1571  case ARM::BI__builtin_arm_dmb:
1572  case ARM::BI__builtin_arm_dsb:
1573  case ARM::BI__builtin_arm_isb:
1574  case ARM::BI__builtin_arm_dbg:
1575  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1576  }
1577 }
1578 
1579 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1580  CallExpr *TheCall) {
1581  if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1582  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1583  BuiltinID == AArch64::BI__builtin_arm_strex ||
1584  BuiltinID == AArch64::BI__builtin_arm_stlex) {
1585  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1586  }
1587 
1588  if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1589  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1590  SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1591  SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1592  SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1593  }
1594 
1595  if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1596  BuiltinID == AArch64::BI__builtin_arm_wsr64)
1597  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1598 
1599  if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1600  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1601  BuiltinID == AArch64::BI__builtin_arm_wsr ||
1602  BuiltinID == AArch64::BI__builtin_arm_wsrp)
1603  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1604 
1605  if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1606  return true;
1607 
1608  // For intrinsics which take an immediate value as part of the instruction,
1609  // range check them here.
1610  unsigned i = 0, l = 0, u = 0;
1611  switch (BuiltinID) {
1612  default: return false;
1613  case AArch64::BI__builtin_arm_dmb:
1614  case AArch64::BI__builtin_arm_dsb:
1615  case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1616  }
1617 
1618  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1619 }
1620 
1621 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1622 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1623 // ordering for DSP is unspecified. MSA is ordered by the data format used
1624 // by the underlying instruction i.e., df/m, df/n and then by size.
1625 //
1626 // FIXME: The size tests here should instead be tablegen'd along with the
1627 // definitions from include/clang/Basic/BuiltinsMips.def.
1628 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1629 // be too.
1630 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1631  unsigned i = 0, l = 0, u = 0, m = 0;
1632  switch (BuiltinID) {
1633  default: return false;
1634  case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1635  case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1636  case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1637  case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1638  case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1639  case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1640  case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1641  // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1642  // df/m field.
1643  // These intrinsics take an unsigned 3 bit immediate.
1644  case Mips::BI__builtin_msa_bclri_b:
1645  case Mips::BI__builtin_msa_bnegi_b:
1646  case Mips::BI__builtin_msa_bseti_b:
1647  case Mips::BI__builtin_msa_sat_s_b:
1648  case Mips::BI__builtin_msa_sat_u_b:
1649  case Mips::BI__builtin_msa_slli_b:
1650  case Mips::BI__builtin_msa_srai_b:
1651  case Mips::BI__builtin_msa_srari_b:
1652  case Mips::BI__builtin_msa_srli_b:
1653  case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1654  case Mips::BI__builtin_msa_binsli_b:
1655  case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1656  // These intrinsics take an unsigned 4 bit immediate.
1657  case Mips::BI__builtin_msa_bclri_h:
1658  case Mips::BI__builtin_msa_bnegi_h:
1659  case Mips::BI__builtin_msa_bseti_h:
1660  case Mips::BI__builtin_msa_sat_s_h:
1661  case Mips::BI__builtin_msa_sat_u_h:
1662  case Mips::BI__builtin_msa_slli_h:
1663  case Mips::BI__builtin_msa_srai_h:
1664  case Mips::BI__builtin_msa_srari_h:
1665  case Mips::BI__builtin_msa_srli_h:
1666  case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1667  case Mips::BI__builtin_msa_binsli_h:
1668  case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1669  // These intrinsics take an unsigned 5 bit immedate.
1670  // The first block of intrinsics actually have an unsigned 5 bit field,
1671  // not a df/n field.
1672  case Mips::BI__builtin_msa_clei_u_b:
1673  case Mips::BI__builtin_msa_clei_u_h:
1674  case Mips::BI__builtin_msa_clei_u_w:
1675  case Mips::BI__builtin_msa_clei_u_d:
1676  case Mips::BI__builtin_msa_clti_u_b:
1677  case Mips::BI__builtin_msa_clti_u_h:
1678  case Mips::BI__builtin_msa_clti_u_w:
1679  case Mips::BI__builtin_msa_clti_u_d:
1680  case Mips::BI__builtin_msa_maxi_u_b:
1681  case Mips::BI__builtin_msa_maxi_u_h:
1682  case Mips::BI__builtin_msa_maxi_u_w:
1683  case Mips::BI__builtin_msa_maxi_u_d:
1684  case Mips::BI__builtin_msa_mini_u_b:
1685  case Mips::BI__builtin_msa_mini_u_h:
1686  case Mips::BI__builtin_msa_mini_u_w:
1687  case Mips::BI__builtin_msa_mini_u_d:
1688  case Mips::BI__builtin_msa_addvi_b:
1689  case Mips::BI__builtin_msa_addvi_h:
1690  case Mips::BI__builtin_msa_addvi_w:
1691  case Mips::BI__builtin_msa_addvi_d:
1692  case Mips::BI__builtin_msa_bclri_w:
1693  case Mips::BI__builtin_msa_bnegi_w:
1694  case Mips::BI__builtin_msa_bseti_w:
1695  case Mips::BI__builtin_msa_sat_s_w:
1696  case Mips::BI__builtin_msa_sat_u_w:
1697  case Mips::BI__builtin_msa_slli_w:
1698  case Mips::BI__builtin_msa_srai_w:
1699  case Mips::BI__builtin_msa_srari_w:
1700  case Mips::BI__builtin_msa_srli_w:
1701  case Mips::BI__builtin_msa_srlri_w:
1702  case Mips::BI__builtin_msa_subvi_b:
1703  case Mips::BI__builtin_msa_subvi_h:
1704  case Mips::BI__builtin_msa_subvi_w:
1705  case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1706  case Mips::BI__builtin_msa_binsli_w:
1707  case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1708  // These intrinsics take an unsigned 6 bit immediate.
1709  case Mips::BI__builtin_msa_bclri_d:
1710  case Mips::BI__builtin_msa_bnegi_d:
1711  case Mips::BI__builtin_msa_bseti_d:
1712  case Mips::BI__builtin_msa_sat_s_d:
1713  case Mips::BI__builtin_msa_sat_u_d:
1714  case Mips::BI__builtin_msa_slli_d:
1715  case Mips::BI__builtin_msa_srai_d:
1716  case Mips::BI__builtin_msa_srari_d:
1717  case Mips::BI__builtin_msa_srli_d:
1718  case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1719  case Mips::BI__builtin_msa_binsli_d:
1720  case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1721  // These intrinsics take a signed 5 bit immediate.
1722  case Mips::BI__builtin_msa_ceqi_b:
1723  case Mips::BI__builtin_msa_ceqi_h:
1724  case Mips::BI__builtin_msa_ceqi_w:
1725  case Mips::BI__builtin_msa_ceqi_d:
1726  case Mips::BI__builtin_msa_clti_s_b:
1727  case Mips::BI__builtin_msa_clti_s_h:
1728  case Mips::BI__builtin_msa_clti_s_w:
1729  case Mips::BI__builtin_msa_clti_s_d:
1730  case Mips::BI__builtin_msa_clei_s_b:
1731  case Mips::BI__builtin_msa_clei_s_h:
1732  case Mips::BI__builtin_msa_clei_s_w:
1733  case Mips::BI__builtin_msa_clei_s_d:
1734  case Mips::BI__builtin_msa_maxi_s_b:
1735  case Mips::BI__builtin_msa_maxi_s_h:
1736  case Mips::BI__builtin_msa_maxi_s_w:
1737  case Mips::BI__builtin_msa_maxi_s_d:
1738  case Mips::BI__builtin_msa_mini_s_b:
1739  case Mips::BI__builtin_msa_mini_s_h:
1740  case Mips::BI__builtin_msa_mini_s_w:
1741  case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1742  // These intrinsics take an unsigned 8 bit immediate.
1743  case Mips::BI__builtin_msa_andi_b:
1744  case Mips::BI__builtin_msa_nori_b:
1745  case Mips::BI__builtin_msa_ori_b:
1746  case Mips::BI__builtin_msa_shf_b:
1747  case Mips::BI__builtin_msa_shf_h:
1748  case Mips::BI__builtin_msa_shf_w:
1749  case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1750  case Mips::BI__builtin_msa_bseli_b:
1751  case Mips::BI__builtin_msa_bmnzi_b:
1752  case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1753  // df/n format
1754  // These intrinsics take an unsigned 4 bit immediate.
1755  case Mips::BI__builtin_msa_copy_s_b:
1756  case Mips::BI__builtin_msa_copy_u_b:
1757  case Mips::BI__builtin_msa_insve_b:
1758  case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1759  case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1760  // These intrinsics take an unsigned 3 bit immediate.
1761  case Mips::BI__builtin_msa_copy_s_h:
1762  case Mips::BI__builtin_msa_copy_u_h:
1763  case Mips::BI__builtin_msa_insve_h:
1764  case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1765  case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1766  // These intrinsics take an unsigned 2 bit immediate.
1767  case Mips::BI__builtin_msa_copy_s_w:
1768  case Mips::BI__builtin_msa_copy_u_w:
1769  case Mips::BI__builtin_msa_insve_w:
1770  case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1771  case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1772  // These intrinsics take an unsigned 1 bit immediate.
1773  case Mips::BI__builtin_msa_copy_s_d:
1774  case Mips::BI__builtin_msa_copy_u_d:
1775  case Mips::BI__builtin_msa_insve_d:
1776  case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1777  case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1778  // Memory offsets and immediate loads.
1779  // These intrinsics take a signed 10 bit immediate.
1780  case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1781  case Mips::BI__builtin_msa_ldi_h:
1782  case Mips::BI__builtin_msa_ldi_w:
1783  case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1784  case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1785  case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1786  case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1787  case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1788  case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1789  case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1790  case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1791  case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1792  }
1793 
1794  if (!m)
1795  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1796 
1797  return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1798  SemaBuiltinConstantArgMultiple(TheCall, i, m);
1799 }
1800 
1801 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1802  unsigned i = 0, l = 0, u = 0;
1803  bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1804  BuiltinID == PPC::BI__builtin_divdeu ||
1805  BuiltinID == PPC::BI__builtin_bpermd;
1806  bool IsTarget64Bit = Context.getTargetInfo()
1807  .getTypeWidth(Context
1808  .getTargetInfo()
1809  .getIntPtrType()) == 64;
1810  bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1811  BuiltinID == PPC::BI__builtin_divweu ||
1812  BuiltinID == PPC::BI__builtin_divde ||
1813  BuiltinID == PPC::BI__builtin_divdeu;
1814 
1815  if (Is64BitBltin && !IsTarget64Bit)
1816  return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1817  << TheCall->getSourceRange();
1818 
1819  if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1820  (BuiltinID == PPC::BI__builtin_bpermd &&
1821  !Context.getTargetInfo().hasFeature("bpermd")))
1822  return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1823  << TheCall->getSourceRange();
1824 
1825  switch (BuiltinID) {
1826  default: return false;
1827  case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1828  case PPC::BI__builtin_altivec_crypto_vshasigmad:
1829  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1830  SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1831  case PPC::BI__builtin_tbegin:
1832  case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1833  case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1834  case PPC::BI__builtin_tabortwc:
1835  case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1836  case PPC::BI__builtin_tabortwci:
1837  case PPC::BI__builtin_tabortdci:
1838  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1839  SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1840  case PPC::BI__builtin_vsx_xxpermdi:
1841  case PPC::BI__builtin_vsx_xxsldwi:
1842  return SemaBuiltinVSX(TheCall);
1843  }
1844  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1845 }
1846 
1847 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1848  CallExpr *TheCall) {
1849  if (BuiltinID == SystemZ::BI__builtin_tabort) {
1850  Expr *Arg = TheCall->getArg(0);
1851  llvm::APSInt AbortCode(32);
1852  if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1853  AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1854  return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1855  << Arg->getSourceRange();
1856  }
1857 
1858  // For intrinsics which take an immediate value as part of the instruction,
1859  // range check them here.
1860  unsigned i = 0, l = 0, u = 0;
1861  switch (BuiltinID) {
1862  default: return false;
1863  case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1864  case SystemZ::BI__builtin_s390_verimb:
1865  case SystemZ::BI__builtin_s390_verimh:
1866  case SystemZ::BI__builtin_s390_verimf:
1867  case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1868  case SystemZ::BI__builtin_s390_vfaeb:
1869  case SystemZ::BI__builtin_s390_vfaeh:
1870  case SystemZ::BI__builtin_s390_vfaef:
1871  case SystemZ::BI__builtin_s390_vfaebs:
1872  case SystemZ::BI__builtin_s390_vfaehs:
1873  case SystemZ::BI__builtin_s390_vfaefs:
1874  case SystemZ::BI__builtin_s390_vfaezb:
1875  case SystemZ::BI__builtin_s390_vfaezh:
1876  case SystemZ::BI__builtin_s390_vfaezf:
1877  case SystemZ::BI__builtin_s390_vfaezbs:
1878  case SystemZ::BI__builtin_s390_vfaezhs:
1879  case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1880  case SystemZ::BI__builtin_s390_vfisb:
1881  case SystemZ::BI__builtin_s390_vfidb:
1882  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1883  SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1884  case SystemZ::BI__builtin_s390_vftcisb:
1885  case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1886  case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1887  case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1888  case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1889  case SystemZ::BI__builtin_s390_vstrcb:
1890  case SystemZ::BI__builtin_s390_vstrch:
1891  case SystemZ::BI__builtin_s390_vstrcf:
1892  case SystemZ::BI__builtin_s390_vstrczb:
1893  case SystemZ::BI__builtin_s390_vstrczh:
1894  case SystemZ::BI__builtin_s390_vstrczf:
1895  case SystemZ::BI__builtin_s390_vstrcbs:
1896  case SystemZ::BI__builtin_s390_vstrchs:
1897  case SystemZ::BI__builtin_s390_vstrcfs:
1898  case SystemZ::BI__builtin_s390_vstrczbs:
1899  case SystemZ::BI__builtin_s390_vstrczhs:
1900  case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1901  case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1902  case SystemZ::BI__builtin_s390_vfminsb:
1903  case SystemZ::BI__builtin_s390_vfmaxsb:
1904  case SystemZ::BI__builtin_s390_vfmindb:
1905  case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1906  }
1907  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1908 }
1909 
1910 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1911 /// This checks that the target supports __builtin_cpu_supports and
1912 /// that the string argument is constant and valid.
1913 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1914  Expr *Arg = TheCall->getArg(0);
1915 
1916  // Check if the argument is a string literal.
1917  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1918  return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1919  << Arg->getSourceRange();
1920 
1921  // Check the contents of the string.
1922  StringRef Feature =
1923  cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1924  if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1925  return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1926  << Arg->getSourceRange();
1927  return false;
1928 }
1929 
1930 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1931 /// This checks that the target supports __builtin_cpu_is and
1932 /// that the string argument is constant and valid.
1933 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1934  Expr *Arg = TheCall->getArg(0);
1935 
1936  // Check if the argument is a string literal.
1937  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1938  return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1939  << Arg->getSourceRange();
1940 
1941  // Check the contents of the string.
1942  StringRef Feature =
1943  cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1944  if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1945  return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1946  << Arg->getSourceRange();
1947  return false;
1948 }
1949 
1950 // Check if the rounding mode is legal.
1951 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1952  // Indicates if this instruction has rounding control or just SAE.
1953  bool HasRC = false;
1954 
1955  unsigned ArgNum = 0;
1956  switch (BuiltinID) {
1957  default:
1958  return false;
1959  case X86::BI__builtin_ia32_vcvttsd2si32:
1960  case X86::BI__builtin_ia32_vcvttsd2si64:
1961  case X86::BI__builtin_ia32_vcvttsd2usi32:
1962  case X86::BI__builtin_ia32_vcvttsd2usi64:
1963  case X86::BI__builtin_ia32_vcvttss2si32:
1964  case X86::BI__builtin_ia32_vcvttss2si64:
1965  case X86::BI__builtin_ia32_vcvttss2usi32:
1966  case X86::BI__builtin_ia32_vcvttss2usi64:
1967  ArgNum = 1;
1968  break;
1969  case X86::BI__builtin_ia32_cvtps2pd512_mask:
1970  case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1971  case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1972  case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1973  case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1974  case X86::BI__builtin_ia32_cvttps2dq512_mask:
1975  case X86::BI__builtin_ia32_cvttps2qq512_mask:
1976  case X86::BI__builtin_ia32_cvttps2udq512_mask:
1977  case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1978  case X86::BI__builtin_ia32_exp2pd_mask:
1979  case X86::BI__builtin_ia32_exp2ps_mask:
1980  case X86::BI__builtin_ia32_getexppd512_mask:
1981  case X86::BI__builtin_ia32_getexpps512_mask:
1982  case X86::BI__builtin_ia32_rcp28pd_mask:
1983  case X86::BI__builtin_ia32_rcp28ps_mask:
1984  case X86::BI__builtin_ia32_rsqrt28pd_mask:
1985  case X86::BI__builtin_ia32_rsqrt28ps_mask:
1986  case X86::BI__builtin_ia32_vcomisd:
1987  case X86::BI__builtin_ia32_vcomiss:
1988  case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1989  ArgNum = 3;
1990  break;
1991  case X86::BI__builtin_ia32_cmppd512_mask:
1992  case X86::BI__builtin_ia32_cmpps512_mask:
1993  case X86::BI__builtin_ia32_cmpsd_mask:
1994  case X86::BI__builtin_ia32_cmpss_mask:
1995  case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1996  case X86::BI__builtin_ia32_getexpsd128_round_mask:
1997  case X86::BI__builtin_ia32_getexpss128_round_mask:
1998  case X86::BI__builtin_ia32_maxpd512_mask:
1999  case X86::BI__builtin_ia32_maxps512_mask:
2000  case X86::BI__builtin_ia32_maxsd_round_mask:
2001  case X86::BI__builtin_ia32_maxss_round_mask:
2002  case X86::BI__builtin_ia32_minpd512_mask:
2003  case X86::BI__builtin_ia32_minps512_mask:
2004  case X86::BI__builtin_ia32_minsd_round_mask:
2005  case X86::BI__builtin_ia32_minss_round_mask:
2006  case X86::BI__builtin_ia32_rcp28sd_round_mask:
2007  case X86::BI__builtin_ia32_rcp28ss_round_mask:
2008  case X86::BI__builtin_ia32_reducepd512_mask:
2009  case X86::BI__builtin_ia32_reduceps512_mask:
2010  case X86::BI__builtin_ia32_rndscalepd_mask:
2011  case X86::BI__builtin_ia32_rndscaleps_mask:
2012  case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2013  case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2014  ArgNum = 4;
2015  break;
2016  case X86::BI__builtin_ia32_fixupimmpd512_mask:
2017  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2018  case X86::BI__builtin_ia32_fixupimmps512_mask:
2019  case X86::BI__builtin_ia32_fixupimmps512_maskz:
2020  case X86::BI__builtin_ia32_fixupimmsd_mask:
2021  case X86::BI__builtin_ia32_fixupimmsd_maskz:
2022  case X86::BI__builtin_ia32_fixupimmss_mask:
2023  case X86::BI__builtin_ia32_fixupimmss_maskz:
2024  case X86::BI__builtin_ia32_rangepd512_mask:
2025  case X86::BI__builtin_ia32_rangeps512_mask:
2026  case X86::BI__builtin_ia32_rangesd128_round_mask:
2027  case X86::BI__builtin_ia32_rangess128_round_mask:
2028  case X86::BI__builtin_ia32_reducesd_mask:
2029  case X86::BI__builtin_ia32_reducess_mask:
2030  case X86::BI__builtin_ia32_rndscalesd_round_mask:
2031  case X86::BI__builtin_ia32_rndscaless_round_mask:
2032  ArgNum = 5;
2033  break;
2034  case X86::BI__builtin_ia32_vcvtsd2si64:
2035  case X86::BI__builtin_ia32_vcvtsd2si32:
2036  case X86::BI__builtin_ia32_vcvtsd2usi32:
2037  case X86::BI__builtin_ia32_vcvtsd2usi64:
2038  case X86::BI__builtin_ia32_vcvtss2si32:
2039  case X86::BI__builtin_ia32_vcvtss2si64:
2040  case X86::BI__builtin_ia32_vcvtss2usi32:
2041  case X86::BI__builtin_ia32_vcvtss2usi64:
2042  ArgNum = 1;
2043  HasRC = true;
2044  break;
2045  case X86::BI__builtin_ia32_cvtsi2sd64:
2046  case X86::BI__builtin_ia32_cvtsi2ss32:
2047  case X86::BI__builtin_ia32_cvtsi2ss64:
2048  case X86::BI__builtin_ia32_cvtusi2sd64:
2049  case X86::BI__builtin_ia32_cvtusi2ss32:
2050  case X86::BI__builtin_ia32_cvtusi2ss64:
2051  ArgNum = 2;
2052  HasRC = true;
2053  break;
2054  case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2055  case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2056  case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2057  case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2058  case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2059  case X86::BI__builtin_ia32_cvtps2qq512_mask:
2060  case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2061  case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2062  case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2063  case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2064  case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2065  case X86::BI__builtin_ia32_sqrtpd512_mask:
2066  case X86::BI__builtin_ia32_sqrtps512_mask:
2067  ArgNum = 3;
2068  HasRC = true;
2069  break;
2070  case X86::BI__builtin_ia32_addpd512_mask:
2071  case X86::BI__builtin_ia32_addps512_mask:
2072  case X86::BI__builtin_ia32_divpd512_mask:
2073  case X86::BI__builtin_ia32_divps512_mask:
2074  case X86::BI__builtin_ia32_mulpd512_mask:
2075  case X86::BI__builtin_ia32_mulps512_mask:
2076  case X86::BI__builtin_ia32_subpd512_mask:
2077  case X86::BI__builtin_ia32_subps512_mask:
2078  case X86::BI__builtin_ia32_addss_round_mask:
2079  case X86::BI__builtin_ia32_addsd_round_mask:
2080  case X86::BI__builtin_ia32_divss_round_mask:
2081  case X86::BI__builtin_ia32_divsd_round_mask:
2082  case X86::BI__builtin_ia32_mulss_round_mask:
2083  case X86::BI__builtin_ia32_mulsd_round_mask:
2084  case X86::BI__builtin_ia32_subss_round_mask:
2085  case X86::BI__builtin_ia32_subsd_round_mask:
2086  case X86::BI__builtin_ia32_scalefpd512_mask:
2087  case X86::BI__builtin_ia32_scalefps512_mask:
2088  case X86::BI__builtin_ia32_scalefsd_round_mask:
2089  case X86::BI__builtin_ia32_scalefss_round_mask:
2090  case X86::BI__builtin_ia32_getmantpd512_mask:
2091  case X86::BI__builtin_ia32_getmantps512_mask:
2092  case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2093  case X86::BI__builtin_ia32_sqrtsd_round_mask:
2094  case X86::BI__builtin_ia32_sqrtss_round_mask:
2095  case X86::BI__builtin_ia32_vfmaddpd512_mask:
2096  case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2097  case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2098  case X86::BI__builtin_ia32_vfmaddps512_mask:
2099  case X86::BI__builtin_ia32_vfmaddps512_mask3:
2100  case X86::BI__builtin_ia32_vfmaddps512_maskz:
2101  case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2102  case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2103  case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2104  case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2105  case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2106  case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2107  case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2108  case X86::BI__builtin_ia32_vfmsubps512_mask3:
2109  case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2110  case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2111  case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2112  case X86::BI__builtin_ia32_vfnmaddps512_mask:
2113  case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2114  case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2115  case X86::BI__builtin_ia32_vfnmsubps512_mask:
2116  case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2117  case X86::BI__builtin_ia32_vfmaddsd3_mask:
2118  case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2119  case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2120  case X86::BI__builtin_ia32_vfmaddss3_mask:
2121  case X86::BI__builtin_ia32_vfmaddss3_maskz:
2122  case X86::BI__builtin_ia32_vfmaddss3_mask3:
2123  ArgNum = 4;
2124  HasRC = true;
2125  break;
2126  case X86::BI__builtin_ia32_getmantsd_round_mask:
2127  case X86::BI__builtin_ia32_getmantss_round_mask:
2128  ArgNum = 5;
2129  HasRC = true;
2130  break;
2131  }
2132 
2133  llvm::APSInt Result;
2134 
2135  // We can't check the value of a dependent argument.
2136  Expr *Arg = TheCall->getArg(ArgNum);
2137  if (Arg->isTypeDependent() || Arg->isValueDependent())
2138  return false;
2139 
2140  // Check constant-ness first.
2141  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2142  return true;
2143 
2144  // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2145  // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2146  // combined with ROUND_NO_EXC.
2147  if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2148  Result == 8/*ROUND_NO_EXC*/ ||
2149  (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2150  return false;
2151 
2152  return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2153  << Arg->getSourceRange();
2154 }
2155 
2156 // Check if the gather/scatter scale is legal.
2157 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2158  CallExpr *TheCall) {
2159  unsigned ArgNum = 0;
2160  switch (BuiltinID) {
2161  default:
2162  return false;
2163  case X86::BI__builtin_ia32_gatherpfdpd:
2164  case X86::BI__builtin_ia32_gatherpfdps:
2165  case X86::BI__builtin_ia32_gatherpfqpd:
2166  case X86::BI__builtin_ia32_gatherpfqps:
2167  case X86::BI__builtin_ia32_scatterpfdpd:
2168  case X86::BI__builtin_ia32_scatterpfdps:
2169  case X86::BI__builtin_ia32_scatterpfqpd:
2170  case X86::BI__builtin_ia32_scatterpfqps:
2171  ArgNum = 3;
2172  break;
2173  case X86::BI__builtin_ia32_gatherd_pd:
2174  case X86::BI__builtin_ia32_gatherd_pd256:
2175  case X86::BI__builtin_ia32_gatherq_pd:
2176  case X86::BI__builtin_ia32_gatherq_pd256:
2177  case X86::BI__builtin_ia32_gatherd_ps:
2178  case X86::BI__builtin_ia32_gatherd_ps256:
2179  case X86::BI__builtin_ia32_gatherq_ps:
2180  case X86::BI__builtin_ia32_gatherq_ps256:
2181  case X86::BI__builtin_ia32_gatherd_q:
2182  case X86::BI__builtin_ia32_gatherd_q256:
2183  case X86::BI__builtin_ia32_gatherq_q:
2184  case X86::BI__builtin_ia32_gatherq_q256:
2185  case X86::BI__builtin_ia32_gatherd_d:
2186  case X86::BI__builtin_ia32_gatherd_d256:
2187  case X86::BI__builtin_ia32_gatherq_d:
2188  case X86::BI__builtin_ia32_gatherq_d256:
2189  case X86::BI__builtin_ia32_gather3div2df:
2190  case X86::BI__builtin_ia32_gather3div2di:
2191  case X86::BI__builtin_ia32_gather3div4df:
2192  case X86::BI__builtin_ia32_gather3div4di:
2193  case X86::BI__builtin_ia32_gather3div4sf:
2194  case X86::BI__builtin_ia32_gather3div4si:
2195  case X86::BI__builtin_ia32_gather3div8sf:
2196  case X86::BI__builtin_ia32_gather3div8si:
2197  case X86::BI__builtin_ia32_gather3siv2df:
2198  case X86::BI__builtin_ia32_gather3siv2di:
2199  case X86::BI__builtin_ia32_gather3siv4df:
2200  case X86::BI__builtin_ia32_gather3siv4di:
2201  case X86::BI__builtin_ia32_gather3siv4sf:
2202  case X86::BI__builtin_ia32_gather3siv4si:
2203  case X86::BI__builtin_ia32_gather3siv8sf:
2204  case X86::BI__builtin_ia32_gather3siv8si:
2205  case X86::BI__builtin_ia32_gathersiv8df:
2206  case X86::BI__builtin_ia32_gathersiv16sf:
2207  case X86::BI__builtin_ia32_gatherdiv8df:
2208  case X86::BI__builtin_ia32_gatherdiv16sf:
2209  case X86::BI__builtin_ia32_gathersiv8di:
2210  case X86::BI__builtin_ia32_gathersiv16si:
2211  case X86::BI__builtin_ia32_gatherdiv8di:
2212  case X86::BI__builtin_ia32_gatherdiv16si:
2213  case X86::BI__builtin_ia32_scatterdiv2df:
2214  case X86::BI__builtin_ia32_scatterdiv2di:
2215  case X86::BI__builtin_ia32_scatterdiv4df:
2216  case X86::BI__builtin_ia32_scatterdiv4di:
2217  case X86::BI__builtin_ia32_scatterdiv4sf:
2218  case X86::BI__builtin_ia32_scatterdiv4si:
2219  case X86::BI__builtin_ia32_scatterdiv8sf:
2220  case X86::BI__builtin_ia32_scatterdiv8si:
2221  case X86::BI__builtin_ia32_scattersiv2df:
2222  case X86::BI__builtin_ia32_scattersiv2di:
2223  case X86::BI__builtin_ia32_scattersiv4df:
2224  case X86::BI__builtin_ia32_scattersiv4di:
2225  case X86::BI__builtin_ia32_scattersiv4sf:
2226  case X86::BI__builtin_ia32_scattersiv4si:
2227  case X86::BI__builtin_ia32_scattersiv8sf:
2228  case X86::BI__builtin_ia32_scattersiv8si:
2229  case X86::BI__builtin_ia32_scattersiv8df:
2230  case X86::BI__builtin_ia32_scattersiv16sf:
2231  case X86::BI__builtin_ia32_scatterdiv8df:
2232  case X86::BI__builtin_ia32_scatterdiv16sf:
2233  case X86::BI__builtin_ia32_scattersiv8di:
2234  case X86::BI__builtin_ia32_scattersiv16si:
2235  case X86::BI__builtin_ia32_scatterdiv8di:
2236  case X86::BI__builtin_ia32_scatterdiv16si:
2237  ArgNum = 4;
2238  break;
2239  }
2240 
2241  llvm::APSInt Result;
2242 
2243  // We can't check the value of a dependent argument.
2244  Expr *Arg = TheCall->getArg(ArgNum);
2245  if (Arg->isTypeDependent() || Arg->isValueDependent())
2246  return false;
2247 
2248  // Check constant-ness first.
2249  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2250  return true;
2251 
2252  if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2253  return false;
2254 
2255  return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2256  << Arg->getSourceRange();
2257 }
2258 
2259 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2260  if (BuiltinID == X86::BI__builtin_cpu_supports)
2261  return SemaBuiltinCpuSupports(*this, TheCall);
2262 
2263  if (BuiltinID == X86::BI__builtin_cpu_is)
2264  return SemaBuiltinCpuIs(*this, TheCall);
2265 
2266  // If the intrinsic has rounding or SAE make sure its valid.
2267  if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2268  return true;
2269 
2270  // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2271  if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2272  return true;
2273 
2274  // For intrinsics which take an immediate value as part of the instruction,
2275  // range check them here.
2276  int i = 0, l = 0, u = 0;
2277  switch (BuiltinID) {
2278  default:
2279  return false;
2280  case X86::BI_mm_prefetch:
2281  i = 1; l = 0; u = 7;
2282  break;
2283  case X86::BI__builtin_ia32_sha1rnds4:
2284  case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2285  case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2286  case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2287  case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2288  i = 2; l = 0; u = 3;
2289  break;
2290  case X86::BI__builtin_ia32_vpermil2pd:
2291  case X86::BI__builtin_ia32_vpermil2pd256:
2292  case X86::BI__builtin_ia32_vpermil2ps:
2293  case X86::BI__builtin_ia32_vpermil2ps256:
2294  i = 3; l = 0; u = 3;
2295  break;
2296  case X86::BI__builtin_ia32_cmpb128_mask:
2297  case X86::BI__builtin_ia32_cmpw128_mask:
2298  case X86::BI__builtin_ia32_cmpd128_mask:
2299  case X86::BI__builtin_ia32_cmpq128_mask:
2300  case X86::BI__builtin_ia32_cmpb256_mask:
2301  case X86::BI__builtin_ia32_cmpw256_mask:
2302  case X86::BI__builtin_ia32_cmpd256_mask:
2303  case X86::BI__builtin_ia32_cmpq256_mask:
2304  case X86::BI__builtin_ia32_cmpb512_mask:
2305  case X86::BI__builtin_ia32_cmpw512_mask:
2306  case X86::BI__builtin_ia32_cmpd512_mask:
2307  case X86::BI__builtin_ia32_cmpq512_mask:
2308  case X86::BI__builtin_ia32_ucmpb128_mask:
2309  case X86::BI__builtin_ia32_ucmpw128_mask:
2310  case X86::BI__builtin_ia32_ucmpd128_mask:
2311  case X86::BI__builtin_ia32_ucmpq128_mask:
2312  case X86::BI__builtin_ia32_ucmpb256_mask:
2313  case X86::BI__builtin_ia32_ucmpw256_mask:
2314  case X86::BI__builtin_ia32_ucmpd256_mask:
2315  case X86::BI__builtin_ia32_ucmpq256_mask:
2316  case X86::BI__builtin_ia32_ucmpb512_mask:
2317  case X86::BI__builtin_ia32_ucmpw512_mask:
2318  case X86::BI__builtin_ia32_ucmpd512_mask:
2319  case X86::BI__builtin_ia32_ucmpq512_mask:
2320  case X86::BI__builtin_ia32_vpcomub:
2321  case X86::BI__builtin_ia32_vpcomuw:
2322  case X86::BI__builtin_ia32_vpcomud:
2323  case X86::BI__builtin_ia32_vpcomuq:
2324  case X86::BI__builtin_ia32_vpcomb:
2325  case X86::BI__builtin_ia32_vpcomw:
2326  case X86::BI__builtin_ia32_vpcomd:
2327  case X86::BI__builtin_ia32_vpcomq:
2328  i = 2; l = 0; u = 7;
2329  break;
2330  case X86::BI__builtin_ia32_roundps:
2331  case X86::BI__builtin_ia32_roundpd:
2332  case X86::BI__builtin_ia32_roundps256:
2333  case X86::BI__builtin_ia32_roundpd256:
2334  i = 1; l = 0; u = 15;
2335  break;
2336  case X86::BI__builtin_ia32_roundss:
2337  case X86::BI__builtin_ia32_roundsd:
2338  case X86::BI__builtin_ia32_rangepd128_mask:
2339  case X86::BI__builtin_ia32_rangepd256_mask:
2340  case X86::BI__builtin_ia32_rangepd512_mask:
2341  case X86::BI__builtin_ia32_rangeps128_mask:
2342  case X86::BI__builtin_ia32_rangeps256_mask:
2343  case X86::BI__builtin_ia32_rangeps512_mask:
2344  case X86::BI__builtin_ia32_getmantsd_round_mask:
2345  case X86::BI__builtin_ia32_getmantss_round_mask:
2346  i = 2; l = 0; u = 15;
2347  break;
2348  case X86::BI__builtin_ia32_cmpps:
2349  case X86::BI__builtin_ia32_cmpss:
2350  case X86::BI__builtin_ia32_cmppd:
2351  case X86::BI__builtin_ia32_cmpsd:
2352  case X86::BI__builtin_ia32_cmpps256:
2353  case X86::BI__builtin_ia32_cmppd256:
2354  case X86::BI__builtin_ia32_cmpps128_mask:
2355  case X86::BI__builtin_ia32_cmppd128_mask:
2356  case X86::BI__builtin_ia32_cmpps256_mask:
2357  case X86::BI__builtin_ia32_cmppd256_mask:
2358  case X86::BI__builtin_ia32_cmpps512_mask:
2359  case X86::BI__builtin_ia32_cmppd512_mask:
2360  case X86::BI__builtin_ia32_cmpsd_mask:
2361  case X86::BI__builtin_ia32_cmpss_mask:
2362  i = 2; l = 0; u = 31;
2363  break;
2364  case X86::BI__builtin_ia32_xabort:
2365  i = 0; l = -128; u = 255;
2366  break;
2367  case X86::BI__builtin_ia32_pshufw:
2368  case X86::BI__builtin_ia32_aeskeygenassist128:
2369  i = 1; l = -128; u = 255;
2370  break;
2371  case X86::BI__builtin_ia32_vcvtps2ph:
2372  case X86::BI__builtin_ia32_vcvtps2ph_mask:
2373  case X86::BI__builtin_ia32_vcvtps2ph256:
2374  case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2375  case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2376  case X86::BI__builtin_ia32_rndscaleps_128_mask:
2377  case X86::BI__builtin_ia32_rndscalepd_128_mask:
2378  case X86::BI__builtin_ia32_rndscaleps_256_mask:
2379  case X86::BI__builtin_ia32_rndscalepd_256_mask:
2380  case X86::BI__builtin_ia32_rndscaleps_mask:
2381  case X86::BI__builtin_ia32_rndscalepd_mask:
2382  case X86::BI__builtin_ia32_reducepd128_mask:
2383  case X86::BI__builtin_ia32_reducepd256_mask:
2384  case X86::BI__builtin_ia32_reducepd512_mask:
2385  case X86::BI__builtin_ia32_reduceps128_mask:
2386  case X86::BI__builtin_ia32_reduceps256_mask:
2387  case X86::BI__builtin_ia32_reduceps512_mask:
2388  case X86::BI__builtin_ia32_prold512_mask:
2389  case X86::BI__builtin_ia32_prolq512_mask:
2390  case X86::BI__builtin_ia32_prold128_mask:
2391  case X86::BI__builtin_ia32_prold256_mask:
2392  case X86::BI__builtin_ia32_prolq128_mask:
2393  case X86::BI__builtin_ia32_prolq256_mask:
2394  case X86::BI__builtin_ia32_prord128_mask:
2395  case X86::BI__builtin_ia32_prord256_mask:
2396  case X86::BI__builtin_ia32_prorq128_mask:
2397  case X86::BI__builtin_ia32_prorq256_mask:
2398  case X86::BI__builtin_ia32_fpclasspd128_mask:
2399  case X86::BI__builtin_ia32_fpclasspd256_mask:
2400  case X86::BI__builtin_ia32_fpclassps128_mask:
2401  case X86::BI__builtin_ia32_fpclassps256_mask:
2402  case X86::BI__builtin_ia32_fpclassps512_mask:
2403  case X86::BI__builtin_ia32_fpclasspd512_mask:
2404  case X86::BI__builtin_ia32_fpclasssd_mask:
2405  case X86::BI__builtin_ia32_fpclassss_mask:
2406  i = 1; l = 0; u = 255;
2407  break;
2408  case X86::BI__builtin_ia32_palignr:
2409  case X86::BI__builtin_ia32_insertps128:
2410  case X86::BI__builtin_ia32_dpps:
2411  case X86::BI__builtin_ia32_dppd:
2412  case X86::BI__builtin_ia32_dpps256:
2413  case X86::BI__builtin_ia32_mpsadbw128:
2414  case X86::BI__builtin_ia32_mpsadbw256:
2415  case X86::BI__builtin_ia32_pcmpistrm128:
2416  case X86::BI__builtin_ia32_pcmpistri128:
2417  case X86::BI__builtin_ia32_pcmpistria128:
2418  case X86::BI__builtin_ia32_pcmpistric128:
2419  case X86::BI__builtin_ia32_pcmpistrio128:
2420  case X86::BI__builtin_ia32_pcmpistris128:
2421  case X86::BI__builtin_ia32_pcmpistriz128:
2422  case X86::BI__builtin_ia32_pclmulqdq128:
2423  case X86::BI__builtin_ia32_vperm2f128_pd256:
2424  case X86::BI__builtin_ia32_vperm2f128_ps256:
2425  case X86::BI__builtin_ia32_vperm2f128_si256:
2426  case X86::BI__builtin_ia32_permti256:
2427  i = 2; l = -128; u = 255;
2428  break;
2429  case X86::BI__builtin_ia32_palignr128:
2430  case X86::BI__builtin_ia32_palignr256:
2431  case X86::BI__builtin_ia32_palignr512_mask:
2432  case X86::BI__builtin_ia32_vcomisd:
2433  case X86::BI__builtin_ia32_vcomiss:
2434  case X86::BI__builtin_ia32_shuf_f32x4_mask:
2435  case X86::BI__builtin_ia32_shuf_f64x2_mask:
2436  case X86::BI__builtin_ia32_shuf_i32x4_mask:
2437  case X86::BI__builtin_ia32_shuf_i64x2_mask:
2438  case X86::BI__builtin_ia32_dbpsadbw128_mask:
2439  case X86::BI__builtin_ia32_dbpsadbw256_mask:
2440  case X86::BI__builtin_ia32_dbpsadbw512_mask:
2441  i = 2; l = 0; u = 255;
2442  break;
2443  case X86::BI__builtin_ia32_fixupimmpd512_mask:
2444  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2445  case X86::BI__builtin_ia32_fixupimmps512_mask:
2446  case X86::BI__builtin_ia32_fixupimmps512_maskz:
2447  case X86::BI__builtin_ia32_fixupimmsd_mask:
2448  case X86::BI__builtin_ia32_fixupimmsd_maskz:
2449  case X86::BI__builtin_ia32_fixupimmss_mask:
2450  case X86::BI__builtin_ia32_fixupimmss_maskz:
2451  case X86::BI__builtin_ia32_fixupimmpd128_mask:
2452  case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2453  case X86::BI__builtin_ia32_fixupimmpd256_mask:
2454  case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2455  case X86::BI__builtin_ia32_fixupimmps128_mask:
2456  case X86::BI__builtin_ia32_fixupimmps128_maskz:
2457  case X86::BI__builtin_ia32_fixupimmps256_mask:
2458  case X86::BI__builtin_ia32_fixupimmps256_maskz:
2459  case X86::BI__builtin_ia32_pternlogd512_mask:
2460  case X86::BI__builtin_ia32_pternlogd512_maskz:
2461  case X86::BI__builtin_ia32_pternlogq512_mask:
2462  case X86::BI__builtin_ia32_pternlogq512_maskz:
2463  case X86::BI__builtin_ia32_pternlogd128_mask:
2464  case X86::BI__builtin_ia32_pternlogd128_maskz:
2465  case X86::BI__builtin_ia32_pternlogd256_mask:
2466  case X86::BI__builtin_ia32_pternlogd256_maskz:
2467  case X86::BI__builtin_ia32_pternlogq128_mask:
2468  case X86::BI__builtin_ia32_pternlogq128_maskz:
2469  case X86::BI__builtin_ia32_pternlogq256_mask:
2470  case X86::BI__builtin_ia32_pternlogq256_maskz:
2471  i = 3; l = 0; u = 255;
2472  break;
2473  case X86::BI__builtin_ia32_gatherpfdpd:
2474  case X86::BI__builtin_ia32_gatherpfdps:
2475  case X86::BI__builtin_ia32_gatherpfqpd:
2476  case X86::BI__builtin_ia32_gatherpfqps:
2477  case X86::BI__builtin_ia32_scatterpfdpd:
2478  case X86::BI__builtin_ia32_scatterpfdps:
2479  case X86::BI__builtin_ia32_scatterpfqpd:
2480  case X86::BI__builtin_ia32_scatterpfqps:
2481  i = 4; l = 2; u = 3;
2482  break;
2483  case X86::BI__builtin_ia32_pcmpestrm128:
2484  case X86::BI__builtin_ia32_pcmpestri128:
2485  case X86::BI__builtin_ia32_pcmpestria128:
2486  case X86::BI__builtin_ia32_pcmpestric128:
2487  case X86::BI__builtin_ia32_pcmpestrio128:
2488  case X86::BI__builtin_ia32_pcmpestris128:
2489  case X86::BI__builtin_ia32_pcmpestriz128:
2490  i = 4; l = -128; u = 255;
2491  break;
2492  case X86::BI__builtin_ia32_rndscalesd_round_mask:
2493  case X86::BI__builtin_ia32_rndscaless_round_mask:
2494  i = 4; l = 0; u = 255;
2495  break;
2496  }
2497  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2498 }
2499 
2500 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2501 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2502 /// Returns true when the format fits the function and the FormatStringInfo has
2503 /// been populated.
2504 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2505  FormatStringInfo *FSI) {
2506  FSI->HasVAListArg = Format->getFirstArg() == 0;
2507  FSI->FormatIdx = Format->getFormatIdx() - 1;
2508  FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2509 
2510  // The way the format attribute works in GCC, the implicit this argument
2511  // of member functions is counted. However, it doesn't appear in our own
2512  // lists, so decrement format_idx in that case.
2513  if (IsCXXMember) {
2514  if(FSI->FormatIdx == 0)
2515  return false;
2516  --FSI->FormatIdx;
2517  if (FSI->FirstDataArg != 0)
2518  --FSI->FirstDataArg;
2519  }
2520  return true;
2521 }
2522 
2523 /// Checks if a the given expression evaluates to null.
2524 ///
2525 /// \brief Returns true if the value evaluates to null.
2526 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2527  // If the expression has non-null type, it doesn't evaluate to null.
2528  if (auto nullability
2529  = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2530  if (*nullability == NullabilityKind::NonNull)
2531  return false;
2532  }
2533 
2534  // As a special case, transparent unions initialized with zero are
2535  // considered null for the purposes of the nonnull attribute.
2536  if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2537  if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2538  if (const CompoundLiteralExpr *CLE =
2539  dyn_cast<CompoundLiteralExpr>(Expr))
2540  if (const InitListExpr *ILE =
2541  dyn_cast<InitListExpr>(CLE->getInitializer()))
2542  Expr = ILE->getInit(0);
2543  }
2544 
2545  bool Result;
2546  return (!Expr->isValueDependent() &&
2547  Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2548  !Result);
2549 }
2550 
2552  const Expr *ArgExpr,
2553  SourceLocation CallSiteLoc) {
2554  if (CheckNonNullExpr(S, ArgExpr))
2555  S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2556  S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2557 }
2558 
2559 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2560  FormatStringInfo FSI;
2561  if ((GetFormatStringType(Format) == FST_NSString) &&
2562  getFormatStringInfo(Format, false, &FSI)) {
2563  Idx = FSI.FormatIdx;
2564  return true;
2565  }
2566  return false;
2567 }
2568 
2569 /// \brief Diagnose use of %s directive in an NSString which is being passed
2570 /// as formatting string to formatting method.
2571 static void
2573  const NamedDecl *FDecl,
2574  Expr **Args,
2575  unsigned NumArgs) {
2576  unsigned Idx = 0;
2577  bool Format = false;
2579  if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2580  Idx = 2;
2581  Format = true;
2582  }
2583  else
2584  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2585  if (S.GetFormatNSStringIdx(I, Idx)) {
2586  Format = true;
2587  break;
2588  }
2589  }
2590  if (!Format || NumArgs <= Idx)
2591  return;
2592  const Expr *FormatExpr = Args[Idx];
2593  if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2594  FormatExpr = CSCE->getSubExpr();
2595  const StringLiteral *FormatString;
2596  if (const ObjCStringLiteral *OSL =
2597  dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2598  FormatString = OSL->getString();
2599  else
2600  FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2601  if (!FormatString)
2602  return;
2603  if (S.FormatStringHasSArg(FormatString)) {
2604  S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2605  << "%s" << 1 << 1;
2606  S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2607  << FDecl->getDeclName();
2608  }
2609 }
2610 
2611 /// Determine whether the given type has a non-null nullability annotation.
2613  if (auto nullability = type->getNullability(ctx))
2614  return *nullability == NullabilityKind::NonNull;
2615 
2616  return false;
2617 }
2618 
2620  const NamedDecl *FDecl,
2621  const FunctionProtoType *Proto,
2622  ArrayRef<const Expr *> Args,
2623  SourceLocation CallSiteLoc) {
2624  assert((FDecl || Proto) && "Need a function declaration or prototype");
2625 
2626  // Check the attributes attached to the method/function itself.
2627  llvm::SmallBitVector NonNullArgs;
2628  if (FDecl) {
2629  // Handle the nonnull attribute on the function/method declaration itself.
2630  for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2631  if (!NonNull->args_size()) {
2632  // Easy case: all pointer arguments are nonnull.
2633  for (const auto *Arg : Args)
2634  if (S.isValidPointerAttrType(Arg->getType()))
2635  CheckNonNullArgument(S, Arg, CallSiteLoc);
2636  return;
2637  }
2638 
2639  for (unsigned Val : NonNull->args()) {
2640  if (Val >= Args.size())
2641  continue;
2642  if (NonNullArgs.empty())
2643  NonNullArgs.resize(Args.size());
2644  NonNullArgs.set(Val);
2645  }
2646  }
2647  }
2648 
2649  if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2650  // Handle the nonnull attribute on the parameters of the
2651  // function/method.
2652  ArrayRef<ParmVarDecl*> parms;
2653  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2654  parms = FD->parameters();
2655  else
2656  parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2657 
2658  unsigned ParamIndex = 0;
2659  for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2660  I != E; ++I, ++ParamIndex) {
2661  const ParmVarDecl *PVD = *I;
2662  if (PVD->hasAttr<NonNullAttr>() ||
2663  isNonNullType(S.Context, PVD->getType())) {
2664  if (NonNullArgs.empty())
2665  NonNullArgs.resize(Args.size());
2666 
2667  NonNullArgs.set(ParamIndex);
2668  }
2669  }
2670  } else {
2671  // If we have a non-function, non-method declaration but no
2672  // function prototype, try to dig out the function prototype.
2673  if (!Proto) {
2674  if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2675  QualType type = VD->getType().getNonReferenceType();
2676  if (auto pointerType = type->getAs<PointerType>())
2677  type = pointerType->getPointeeType();
2678  else if (auto blockType = type->getAs<BlockPointerType>())
2679  type = blockType->getPointeeType();
2680  // FIXME: data member pointers?
2681 
2682  // Dig out the function prototype, if there is one.
2683  Proto = type->getAs<FunctionProtoType>();
2684  }
2685  }
2686 
2687  // Fill in non-null argument information from the nullability
2688  // information on the parameter types (if we have them).
2689  if (Proto) {
2690  unsigned Index = 0;
2691  for (auto paramType : Proto->getParamTypes()) {
2692  if (isNonNullType(S.Context, paramType)) {
2693  if (NonNullArgs.empty())
2694  NonNullArgs.resize(Args.size());
2695 
2696  NonNullArgs.set(Index);
2697  }
2698 
2699  ++Index;
2700  }
2701  }
2702  }
2703 
2704  // Check for non-null arguments.
2705  for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2706  ArgIndex != ArgIndexEnd; ++ArgIndex) {
2707  if (NonNullArgs[ArgIndex])
2708  CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2709  }
2710 }
2711 
2712 /// Handles the checks for format strings, non-POD arguments to vararg
2713 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2714 /// attributes.
2715 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2716  const Expr *ThisArg, ArrayRef<const Expr *> Args,
2717  bool IsMemberFunction, SourceLocation Loc,
2718  SourceRange Range, VariadicCallType CallType) {
2719  // FIXME: We should check as much as we can in the template definition.
2720  if (CurContext->isDependentContext())
2721  return;
2722 
2723  // Printf and scanf checking.
2724  llvm::SmallBitVector CheckedVarArgs;
2725  if (FDecl) {
2726  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2727  // Only create vector if there are format attributes.
2728  CheckedVarArgs.resize(Args.size());
2729 
2730  CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2731  CheckedVarArgs);
2732  }
2733  }
2734 
2735  // Refuse POD arguments that weren't caught by the format string
2736  // checks above.
2737  auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2738  if (CallType != VariadicDoesNotApply &&
2739  (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2740  unsigned NumParams = Proto ? Proto->getNumParams()
2741  : FDecl && isa<FunctionDecl>(FDecl)
2742  ? cast<FunctionDecl>(FDecl)->getNumParams()
2743  : FDecl && isa<ObjCMethodDecl>(FDecl)
2744  ? cast<ObjCMethodDecl>(FDecl)->param_size()
2745  : 0;
2746 
2747  for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2748  // Args[ArgIdx] can be null in malformed code.
2749  if (const Expr *Arg = Args[ArgIdx]) {
2750  if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2751  checkVariadicArgument(Arg, CallType);
2752  }
2753  }
2754  }
2755 
2756  if (FDecl || Proto) {
2757  CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2758 
2759  // Type safety checking.
2760  if (FDecl) {
2761  for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2762  CheckArgumentWithTypeTag(I, Args, Loc);
2763  }
2764  }
2765 
2766  if (FD)
2767  diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2768 }
2769 
2770 /// CheckConstructorCall - Check a constructor call for correctness and safety
2771 /// properties not enforced by the C type system.
2772 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2773  ArrayRef<const Expr *> Args,
2774  const FunctionProtoType *Proto,
2775  SourceLocation Loc) {
2776  VariadicCallType CallType =
2777  Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2778  checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2779  Loc, SourceRange(), CallType);
2780 }
2781 
2782 /// CheckFunctionCall - Check a direct function call for various correctness
2783 /// and safety properties not strictly enforced by the C type system.
2784 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2785  const FunctionProtoType *Proto) {
2786  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2787  isa<CXXMethodDecl>(FDecl);
2788  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2789  IsMemberOperatorCall;
2790  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2791  TheCall->getCallee());
2792  Expr** Args = TheCall->getArgs();
2793  unsigned NumArgs = TheCall->getNumArgs();
2794 
2795  Expr *ImplicitThis = nullptr;
2796  if (IsMemberOperatorCall) {
2797  // If this is a call to a member operator, hide the first argument
2798  // from checkCall.
2799  // FIXME: Our choice of AST representation here is less than ideal.
2800  ImplicitThis = Args[0];
2801  ++Args;
2802  --NumArgs;
2803  } else if (IsMemberFunction)
2804  ImplicitThis =
2805  cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2806 
2807  checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2808  IsMemberFunction, TheCall->getRParenLoc(),
2809  TheCall->getCallee()->getSourceRange(), CallType);
2810 
2811  IdentifierInfo *FnInfo = FDecl->getIdentifier();
2812  // None of the checks below are needed for functions that don't have
2813  // simple names (e.g., C++ conversion functions).
2814  if (!FnInfo)
2815  return false;
2816 
2817  CheckAbsoluteValueFunction(TheCall, FDecl);
2818  CheckMaxUnsignedZero(TheCall, FDecl);
2819 
2820  if (getLangOpts().ObjC1)
2821  DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2822 
2823  unsigned CMId = FDecl->getMemoryFunctionKind();
2824  if (CMId == 0)
2825  return false;
2826 
2827  // Handle memory setting and copying functions.
2828  if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2829  CheckStrlcpycatArguments(TheCall, FnInfo);
2830  else if (CMId == Builtin::BIstrncat)
2831  CheckStrncatArguments(TheCall, FnInfo);
2832  else
2833  CheckMemaccessArguments(TheCall, CMId, FnInfo);
2834 
2835  return false;
2836 }
2837 
2838 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2839  ArrayRef<const Expr *> Args) {
2840  VariadicCallType CallType =
2841  Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2842 
2843  checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2844  /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2845  CallType);
2846 
2847  return false;
2848 }
2849 
2850 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2851  const FunctionProtoType *Proto) {
2852  QualType Ty;
2853  if (const auto *V = dyn_cast<VarDecl>(NDecl))
2854  Ty = V->getType().getNonReferenceType();
2855  else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2856  Ty = F->getType().getNonReferenceType();
2857  else
2858  return false;
2859 
2860  if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2861  !Ty->isFunctionProtoType())
2862  return false;
2863 
2864  VariadicCallType CallType;
2865  if (!Proto || !Proto->isVariadic()) {
2866  CallType = VariadicDoesNotApply;
2867  } else if (Ty->isBlockPointerType()) {
2868  CallType = VariadicBlock;
2869  } else { // Ty->isFunctionPointerType()
2870  CallType = VariadicFunction;
2871  }
2872 
2873  checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2874  llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2875  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2876  TheCall->getCallee()->getSourceRange(), CallType);
2877 
2878  return false;
2879 }
2880 
2881 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2882 /// such as function pointers returned from functions.
2883 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2884  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2885  TheCall->getCallee());
2886  checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2887  llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2888  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2889  TheCall->getCallee()->getSourceRange(), CallType);
2890 
2891  return false;
2892 }
2893 
2894 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2895  if (!llvm::isValidAtomicOrderingCABI(Ordering))
2896  return false;
2897 
2898  auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2899  switch (Op) {
2900  case AtomicExpr::AO__c11_atomic_init:
2901  case AtomicExpr::AO__opencl_atomic_init:
2902  llvm_unreachable("There is no ordering argument for an init");
2903 
2904  case AtomicExpr::AO__c11_atomic_load:
2905  case AtomicExpr::AO__opencl_atomic_load:
2906  case AtomicExpr::AO__atomic_load_n:
2907  case AtomicExpr::AO__atomic_load:
2908  return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2909  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2910 
2911  case AtomicExpr::AO__c11_atomic_store:
2912  case AtomicExpr::AO__opencl_atomic_store:
2913  case AtomicExpr::AO__atomic_store:
2914  case AtomicExpr::AO__atomic_store_n:
2915  return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2916  OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2917  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2918 
2919  default:
2920  return true;
2921  }
2922 }
2923 
2924 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2925  AtomicExpr::AtomicOp Op) {
2926  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2927  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2928 
2929  // All the non-OpenCL operations take one of the following forms.
2930  // The OpenCL operations take the __c11 forms with one extra argument for
2931  // synchronization scope.
2932  enum {
2933  // C __c11_atomic_init(A *, C)
2934  Init,
2935 
2936  // C __c11_atomic_load(A *, int)
2937  Load,
2938 
2939  // void __atomic_load(A *, CP, int)
2940  LoadCopy,
2941 
2942  // void __atomic_store(A *, CP, int)
2943  Copy,
2944 
2945  // C __c11_atomic_add(A *, M, int)
2946  Arithmetic,
2947 
2948  // C __atomic_exchange_n(A *, CP, int)
2949  Xchg,
2950 
2951  // void __atomic_exchange(A *, C *, CP, int)
2952  GNUXchg,
2953 
2954  // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2955  C11CmpXchg,
2956 
2957  // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2958  GNUCmpXchg
2959  } Form = Init;
2960 
2961  const unsigned NumForm = GNUCmpXchg + 1;
2962  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2963  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2964  // where:
2965  // C is an appropriate type,
2966  // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2967  // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2968  // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2969  // the int parameters are for orderings.
2970 
2971  static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2972  && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2973  "need to update code for modified forms");
2974  static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2975  AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2976  AtomicExpr::AO__atomic_load,
2977  "need to update code for modified C11 atomics");
2978  bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2979  Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2980  bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2981  Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2982  IsOpenCL;
2983  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2984  Op == AtomicExpr::AO__atomic_store_n ||
2985  Op == AtomicExpr::AO__atomic_exchange_n ||
2986  Op == AtomicExpr::AO__atomic_compare_exchange_n;
2987  bool IsAddSub = false;
2988 
2989  switch (Op) {
2990  case AtomicExpr::AO__c11_atomic_init:
2991  case AtomicExpr::AO__opencl_atomic_init:
2992  Form = Init;
2993  break;
2994 
2995  case AtomicExpr::AO__c11_atomic_load:
2996  case AtomicExpr::AO__opencl_atomic_load:
2997  case AtomicExpr::AO__atomic_load_n:
2998  Form = Load;
2999  break;
3000 
3001  case AtomicExpr::AO__atomic_load:
3002  Form = LoadCopy;
3003  break;
3004 
3005  case AtomicExpr::AO__c11_atomic_store:
3006  case AtomicExpr::AO__opencl_atomic_store:
3007  case AtomicExpr::AO__atomic_store:
3008  case AtomicExpr::AO__atomic_store_n:
3009  Form = Copy;
3010  break;
3011 
3012  case AtomicExpr::AO__c11_atomic_fetch_add:
3013  case AtomicExpr::AO__c11_atomic_fetch_sub:
3014  case AtomicExpr::AO__opencl_atomic_fetch_add:
3015  case AtomicExpr::AO__opencl_atomic_fetch_sub:
3016  case AtomicExpr::AO__opencl_atomic_fetch_min:
3017  case AtomicExpr::AO__opencl_atomic_fetch_max:
3018  case AtomicExpr::AO__atomic_fetch_add:
3019  case AtomicExpr::AO__atomic_fetch_sub:
3020  case AtomicExpr::AO__atomic_add_fetch:
3021  case AtomicExpr::AO__atomic_sub_fetch:
3022  IsAddSub = true;
3023  LLVM_FALLTHROUGH;
3024  case AtomicExpr::AO__c11_atomic_fetch_and:
3025  case AtomicExpr::AO__c11_atomic_fetch_or:
3026  case AtomicExpr::AO__c11_atomic_fetch_xor:
3027  case AtomicExpr::AO__opencl_atomic_fetch_and:
3028  case AtomicExpr::AO__opencl_atomic_fetch_or:
3029  case AtomicExpr::AO__opencl_atomic_fetch_xor:
3030  case AtomicExpr::AO__atomic_fetch_and:
3031  case AtomicExpr::AO__atomic_fetch_or:
3032  case AtomicExpr::AO__atomic_fetch_xor:
3033  case AtomicExpr::AO__atomic_fetch_nand:
3034  case AtomicExpr::AO__atomic_and_fetch:
3035  case AtomicExpr::AO__atomic_or_fetch:
3036  case AtomicExpr::AO__atomic_xor_fetch:
3037  case AtomicExpr::AO__atomic_nand_fetch:
3038  Form = Arithmetic;
3039  break;
3040 
3041  case AtomicExpr::AO__c11_atomic_exchange:
3042  case AtomicExpr::AO__opencl_atomic_exchange:
3043  case AtomicExpr::AO__atomic_exchange_n:
3044  Form = Xchg;
3045  break;
3046 
3047  case AtomicExpr::AO__atomic_exchange:
3048  Form = GNUXchg;
3049  break;
3050 
3051  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3052  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3053  case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3054  case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3055  Form = C11CmpXchg;
3056  break;
3057 
3058  case AtomicExpr::AO__atomic_compare_exchange:
3059  case AtomicExpr::AO__atomic_compare_exchange_n:
3060  Form = GNUCmpXchg;
3061  break;
3062  }
3063 
3064  unsigned AdjustedNumArgs = NumArgs[Form];
3065  if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3066  ++AdjustedNumArgs;
3067  // Check we have the right number of arguments.
3068  if (TheCall->getNumArgs() < AdjustedNumArgs) {
3069  Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3070  << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3071  << TheCall->getCallee()->getSourceRange();
3072  return ExprError();
3073  } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3074  Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3075  diag::err_typecheck_call_too_many_args)
3076  << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3077  << TheCall->getCallee()->getSourceRange();
3078  return ExprError();
3079  }
3080 
3081  // Inspect the first argument of the atomic operation.
3082  Expr *Ptr = TheCall->getArg(0);
3083  ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3084  if (ConvertedPtr.isInvalid())
3085  return ExprError();
3086 
3087  Ptr = ConvertedPtr.get();
3088  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3089  if (!pointerType) {
3090  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3091  << Ptr->getType() << Ptr->getSourceRange();
3092  return ExprError();
3093  }
3094 
3095  // For a __c11 builtin, this should be a pointer to an _Atomic type.
3096  QualType AtomTy = pointerType->getPointeeType(); // 'A'
3097  QualType ValType = AtomTy; // 'C'
3098  if (IsC11) {
3099  if (!AtomTy->isAtomicType()) {
3100  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3101  << Ptr->getType() << Ptr->getSourceRange();
3102  return ExprError();
3103  }
3104  if (AtomTy.isConstQualified() ||
3106  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3107  << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3108  << Ptr->getSourceRange();
3109  return ExprError();
3110  }
3111  ValType = AtomTy->getAs<AtomicType>()->getValueType();
3112  } else if (Form != Load && Form != LoadCopy) {
3113  if (ValType.isConstQualified()) {
3114  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3115  << Ptr->getType() << Ptr->getSourceRange();
3116  return ExprError();
3117  }
3118  }
3119 
3120  // For an arithmetic operation, the implied arithmetic must be well-formed.
3121  if (Form == Arithmetic) {
3122  // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3123  if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3124  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3125  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3126  return ExprError();
3127  }
3128  if (!IsAddSub && !ValType->isIntegerType()) {
3129  Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3130  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3131  return ExprError();
3132  }
3133  if (IsC11 && ValType->isPointerType() &&
3134  RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3135  diag::err_incomplete_type)) {
3136  return ExprError();
3137  }
3138  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3139  // For __atomic_*_n operations, the value type must be a scalar integral or
3140  // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3141  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3142  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3143  return ExprError();
3144  }
3145 
3146  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3147  !AtomTy->isScalarType()) {
3148  // For GNU atomics, require a trivially-copyable type. This is not part of
3149  // the GNU atomics specification, but we enforce it for sanity.
3150  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3151  << Ptr->getType() << Ptr->getSourceRange();
3152  return ExprError();
3153  }
3154 
3155  switch (ValType.getObjCLifetime()) {
3156  case Qualifiers::OCL_None:
3158  // okay
3159  break;
3160 
3161  case Qualifiers::OCL_Weak:
3164  // FIXME: Can this happen? By this point, ValType should be known
3165  // to be trivially copyable.
3166  Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3167  << ValType << Ptr->getSourceRange();
3168  return ExprError();
3169  }
3170 
3171  // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3172  // volatile-ness of the pointee-type inject itself into the result or the
3173  // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3174  ValType.removeLocalVolatile();
3175  ValType.removeLocalConst();
3176  QualType ResultType = ValType;
3177  if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3178  Form == Init)
3179  ResultType = Context.VoidTy;
3180  else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3181  ResultType = Context.BoolTy;
3182 
3183  // The type of a parameter passed 'by value'. In the GNU atomics, such
3184  // arguments are actually passed as pointers.
3185  QualType ByValType = ValType; // 'CP'
3186  if (!IsC11 && !IsN)
3187  ByValType = Ptr->getType();
3188 
3189  // The first argument --- the pointer --- has a fixed type; we
3190  // deduce the types of the rest of the arguments accordingly. Walk
3191  // the remaining arguments, converting them to the deduced value type.
3192  for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3193  QualType Ty;
3194  if (i < NumVals[Form] + 1) {
3195  switch (i) {
3196  case 1:
3197  // The second argument is the non-atomic operand. For arithmetic, this
3198  // is always passed by value, and for a compare_exchange it is always
3199  // passed by address. For the rest, GNU uses by-address and C11 uses
3200  // by-value.
3201  assert(Form != Load);
3202  if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3203  Ty = ValType;
3204  else if (Form == Copy || Form == Xchg)
3205  Ty = ByValType;
3206  else if (Form == Arithmetic)
3207  Ty = Context.getPointerDiffType();
3208  else {
3209  Expr *ValArg = TheCall->getArg(i);
3210  // Treat this argument as _Nonnull as we want to show a warning if
3211  // NULL is passed into it.
3212  CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3213  LangAS AS = LangAS::Default;
3214  // Keep address space of non-atomic pointer type.
3215  if (const PointerType *PtrTy =
3216  ValArg->getType()->getAs<PointerType>()) {
3217  AS = PtrTy->getPointeeType().getAddressSpace();
3218  }
3219  Ty = Context.getPointerType(
3220  Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3221  }
3222  break;
3223  case 2:
3224  // The third argument to compare_exchange / GNU exchange is a
3225  // (pointer to a) desired value.
3226  Ty = ByValType;
3227  break;
3228  case 3:
3229  // The fourth argument to GNU compare_exchange is a 'weak' flag.
3230  Ty = Context.BoolTy;
3231  break;
3232  }
3233  } else {
3234  // The order(s) and scope are always converted to int.
3235  Ty = Context.IntTy;
3236  }
3237 
3238  InitializedEntity Entity =
3239  InitializedEntity::InitializeParameter(Context, Ty, false);
3240  ExprResult Arg = TheCall->getArg(i);
3241  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3242  if (Arg.isInvalid())
3243  return true;
3244  TheCall->setArg(i, Arg.get());
3245  }
3246 
3247  // Permute the arguments into a 'consistent' order.
3248  SmallVector<Expr*, 5> SubExprs;
3249  SubExprs.push_back(Ptr);
3250  switch (Form) {
3251  case Init:
3252  // Note, AtomicExpr::getVal1() has a special case for this atomic.
3253  SubExprs.push_back(TheCall->getArg(1)); // Val1
3254  break;
3255  case Load:
3256  SubExprs.push_back(TheCall->getArg(1)); // Order
3257  break;
3258  case LoadCopy:
3259  case Copy:
3260  case Arithmetic:
3261  case Xchg:
3262  SubExprs.push_back(TheCall->getArg(2)); // Order
3263  SubExprs.push_back(TheCall->getArg(1)); // Val1
3264  break;
3265  case GNUXchg:
3266  // Note, AtomicExpr::getVal2() has a special case for this atomic.
3267  SubExprs.push_back(TheCall->getArg(3)); // Order
3268  SubExprs.push_back(TheCall->getArg(1)); // Val1
3269  SubExprs.push_back(TheCall->getArg(2)); // Val2
3270  break;
3271  case C11CmpXchg:
3272  SubExprs.push_back(TheCall->getArg(3)); // Order
3273  SubExprs.push_back(TheCall->getArg(1)); // Val1
3274  SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3275  SubExprs.push_back(TheCall->getArg(2)); // Val2
3276  break;
3277  case GNUCmpXchg:
3278  SubExprs.push_back(TheCall->getArg(4)); // Order
3279  SubExprs.push_back(TheCall->getArg(1)); // Val1
3280  SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3281  SubExprs.push_back(TheCall->getArg(2)); // Val2
3282  SubExprs.push_back(TheCall->getArg(3)); // Weak
3283  break;
3284  }
3285 
3286  if (SubExprs.size() >= 2 && Form != Init) {
3287  llvm::APSInt Result(32);
3288  if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3289  !isValidOrderingForOp(Result.getSExtValue(), Op))
3290  Diag(SubExprs[1]->getLocStart(),
3291  diag::warn_atomic_op_has_invalid_memory_order)
3292  << SubExprs[1]->getSourceRange();
3293  }
3294 
3295  if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3296  auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3297  llvm::APSInt Result(32);
3298  if (Scope->isIntegerConstantExpr(Result, Context) &&
3299  !ScopeModel->isValid(Result.getZExtValue())) {
3300  Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3301  << Scope->getSourceRange();
3302  }
3303  SubExprs.push_back(Scope);
3304  }
3305 
3306  AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3307  SubExprs, ResultType, Op,
3308  TheCall->getRParenLoc());
3309 
3310  if ((Op == AtomicExpr::AO__c11_atomic_load ||
3311  Op == AtomicExpr::AO__c11_atomic_store ||
3312  Op == AtomicExpr::AO__opencl_atomic_load ||
3313  Op == AtomicExpr::AO__opencl_atomic_store ) &&
3314  Context.AtomicUsesUnsupportedLibcall(AE))
3315  Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3316  << ((Op == AtomicExpr::AO__c11_atomic_load ||
3317  Op == AtomicExpr::AO__opencl_atomic_load)
3318  ? 0 : 1);
3319 
3320  return AE;
3321 }
3322 
3323 /// checkBuiltinArgument - Given a call to a builtin function, perform
3324 /// normal type-checking on the given argument, updating the call in
3325 /// place. This is useful when a builtin function requires custom
3326 /// type-checking for some of its arguments but not necessarily all of
3327 /// them.
3328 ///
3329 /// Returns true on error.
3330 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3331  FunctionDecl *Fn = E->getDirectCallee();
3332  assert(Fn && "builtin call without direct callee!");
3333 
3334  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3335  InitializedEntity Entity =
3337 
3338  ExprResult Arg = E->getArg(0);
3339  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3340  if (Arg.isInvalid())
3341  return true;
3342 
3343  E->setArg(ArgIndex, Arg.get());
3344  return false;
3345 }
3346 
3347 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3348 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3349 /// type of its first argument. The main ActOnCallExpr routines have already
3350 /// promoted the types of arguments because all of these calls are prototyped as
3351 /// void(...).
3352 ///
3353 /// This function goes through and does final semantic checking for these
3354 /// builtins,
3355 ExprResult
3356 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3357  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3358  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3359  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3360 
3361  // Ensure that we have at least one argument to do type inference from.
3362  if (TheCall->getNumArgs() < 1) {
3363  Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3364  << 0 << 1 << TheCall->getNumArgs()
3365  << TheCall->getCallee()->getSourceRange();
3366  return ExprError();
3367  }
3368 
3369  // Inspect the first argument of the atomic builtin. This should always be
3370  // a pointer type, whose element is an integral scalar or pointer type.
3371  // Because it is a pointer type, we don't have to worry about any implicit
3372  // casts here.
3373  // FIXME: We don't allow floating point scalars as input.
3374  Expr *FirstArg = TheCall->getArg(0);
3375  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3376  if (FirstArgResult.isInvalid())
3377  return ExprError();
3378  FirstArg = FirstArgResult.get();
3379  TheCall->setArg(0, FirstArg);
3380 
3381  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3382  if (!pointerType) {
3383  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3384  << FirstArg->getType() << FirstArg->getSourceRange();
3385  return ExprError();
3386  }
3387 
3388  QualType ValType = pointerType->getPointeeType();
3389  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3390  !ValType->isBlockPointerType()) {
3391  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3392  << FirstArg->getType() << FirstArg->getSourceRange();
3393  return ExprError();
3394  }
3395 
3396  switch (ValType.getObjCLifetime()) {
3397  case Qualifiers::OCL_None:
3399  // okay
3400  break;
3401 
3402  case Qualifiers::OCL_Weak:
3405  Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3406  << ValType << FirstArg->getSourceRange();
3407  return ExprError();
3408  }
3409 
3410  // Strip any qualifiers off ValType.
3411  ValType = ValType.getUnqualifiedType();
3412 
3413  // The majority of builtins return a value, but a few have special return
3414  // types, so allow them to override appropriately below.
3415  QualType ResultType = ValType;
3416 
3417  // We need to figure out which concrete builtin this maps onto. For example,
3418  // __sync_fetch_and_add with a 2 byte object turns into
3419  // __sync_fetch_and_add_2.
3420 #define BUILTIN_ROW(x) \
3421  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3422  Builtin::BI##x##_8, Builtin::BI##x##_16 }
3423 
3424  static const unsigned BuiltinIndices[][5] = {
3425  BUILTIN_ROW(__sync_fetch_and_add),
3426  BUILTIN_ROW(__sync_fetch_and_sub),
3427  BUILTIN_ROW(__sync_fetch_and_or),
3428  BUILTIN_ROW(__sync_fetch_and_and),
3429  BUILTIN_ROW(__sync_fetch_and_xor),
3430  BUILTIN_ROW(__sync_fetch_and_nand),
3431 
3432  BUILTIN_ROW(__sync_add_and_fetch),
3433  BUILTIN_ROW(__sync_sub_and_fetch),
3434  BUILTIN_ROW(__sync_and_and_fetch),
3435  BUILTIN_ROW(__sync_or_and_fetch),
3436  BUILTIN_ROW(__sync_xor_and_fetch),
3437  BUILTIN_ROW(__sync_nand_and_fetch),
3438 
3439  BUILTIN_ROW(__sync_val_compare_and_swap),
3440  BUILTIN_ROW(__sync_bool_compare_and_swap),
3441  BUILTIN_ROW(__sync_lock_test_and_set),
3442  BUILTIN_ROW(__sync_lock_release),
3443  BUILTIN_ROW(__sync_swap)
3444  };
3445 #undef BUILTIN_ROW
3446 
3447  // Determine the index of the size.
3448  unsigned SizeIndex;
3449  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3450  case 1: SizeIndex = 0; break;
3451  case 2: SizeIndex = 1; break;
3452  case 4: SizeIndex = 2; break;
3453  case 8: SizeIndex = 3; break;
3454  case 16: SizeIndex = 4; break;
3455  default:
3456  Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3457  << FirstArg->getType() << FirstArg->getSourceRange();
3458  return ExprError();
3459  }
3460 
3461  // Each of these builtins has one pointer argument, followed by some number of
3462  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3463  // that we ignore. Find out which row of BuiltinIndices to read from as well
3464  // as the number of fixed args.
3465  unsigned BuiltinID = FDecl->getBuiltinID();
3466  unsigned BuiltinIndex, NumFixed = 1;
3467  bool WarnAboutSemanticsChange = false;
3468  switch (BuiltinID) {
3469  default: llvm_unreachable("Unknown overloaded atomic builtin!");
3470  case Builtin::BI__sync_fetch_and_add:
3471  case Builtin::BI__sync_fetch_and_add_1:
3472  case Builtin::BI__sync_fetch_and_add_2:
3473  case Builtin::BI__sync_fetch_and_add_4:
3474  case Builtin::BI__sync_fetch_and_add_8:
3475  case Builtin::BI__sync_fetch_and_add_16:
3476  BuiltinIndex = 0;
3477  break;
3478 
3479  case Builtin::BI__sync_fetch_and_sub:
3480  case Builtin::BI__sync_fetch_and_sub_1:
3481  case Builtin::BI__sync_fetch_and_sub_2:
3482  case Builtin::BI__sync_fetch_and_sub_4:
3483  case Builtin::BI__sync_fetch_and_sub_8:
3484  case Builtin::BI__sync_fetch_and_sub_16:
3485  BuiltinIndex = 1;
3486  break;
3487 
3488  case Builtin::BI__sync_fetch_and_or:
3489  case Builtin::BI__sync_fetch_and_or_1:
3490  case Builtin::BI__sync_fetch_and_or_2:
3491  case Builtin::BI__sync_fetch_and_or_4:
3492  case Builtin::BI__sync_fetch_and_or_8:
3493  case Builtin::BI__sync_fetch_and_or_16:
3494  BuiltinIndex = 2;
3495  break;
3496 
3497  case Builtin::BI__sync_fetch_and_and:
3498  case Builtin::BI__sync_fetch_and_and_1:
3499  case Builtin::BI__sync_fetch_and_and_2:
3500  case Builtin::BI__sync_fetch_and_and_4:
3501  case Builtin::BI__sync_fetch_and_and_8:
3502  case Builtin::BI__sync_fetch_and_and_16:
3503  BuiltinIndex = 3;
3504  break;
3505 
3506  case Builtin::BI__sync_fetch_and_xor:
3507  case Builtin::BI__sync_fetch_and_xor_1:
3508  case Builtin::BI__sync_fetch_and_xor_2:
3509  case Builtin::BI__sync_fetch_and_xor_4:
3510  case Builtin::BI__sync_fetch_and_xor_8:
3511  case Builtin::BI__sync_fetch_and_xor_16:
3512  BuiltinIndex = 4;
3513  break;
3514 
3515  case Builtin::BI__sync_fetch_and_nand:
3516  case Builtin::BI__sync_fetch_and_nand_1:
3517  case Builtin::BI__sync_fetch_and_nand_2:
3518  case Builtin::BI__sync_fetch_and_nand_4:
3519  case Builtin::BI__sync_fetch_and_nand_8:
3520  case Builtin::BI__sync_fetch_and_nand_16:
3521  BuiltinIndex = 5;
3522  WarnAboutSemanticsChange = true;
3523  break;
3524 
3525  case Builtin::BI__sync_add_and_fetch:
3526  case Builtin::BI__sync_add_and_fetch_1:
3527  case Builtin::BI__sync_add_and_fetch_2:
3528  case Builtin::BI__sync_add_and_fetch_4:
3529  case Builtin::BI__sync_add_and_fetch_8:
3530  case Builtin::BI__sync_add_and_fetch_16:
3531  BuiltinIndex = 6;
3532  break;
3533 
3534  case Builtin::BI__sync_sub_and_fetch:
3535  case Builtin::BI__sync_sub_and_fetch_1:
3536  case Builtin::BI__sync_sub_and_fetch_2:
3537  case Builtin::BI__sync_sub_and_fetch_4:
3538  case Builtin::BI__sync_sub_and_fetch_8:
3539  case Builtin::BI__sync_sub_and_fetch_16:
3540  BuiltinIndex = 7;
3541  break;
3542 
3543  case Builtin::BI__sync_and_and_fetch:
3544  case Builtin::BI__sync_and_and_fetch_1:
3545  case Builtin::BI__sync_and_and_fetch_2:
3546  case Builtin::BI__sync_and_and_fetch_4:
3547  case Builtin::BI__sync_and_and_fetch_8:
3548  case Builtin::BI__sync_and_and_fetch_16:
3549  BuiltinIndex = 8;
3550  break;
3551 
3552  case Builtin::BI__sync_or_and_fetch:
3553  case Builtin::BI__sync_or_and_fetch_1:
3554  case Builtin::BI__sync_or_and_fetch_2:
3555  case Builtin::BI__sync_or_and_fetch_4:
3556  case Builtin::BI__sync_or_and_fetch_8:
3557  case Builtin::BI__sync_or_and_fetch_16:
3558  BuiltinIndex = 9;
3559  break;
3560 
3561  case Builtin::BI__sync_xor_and_fetch:
3562  case Builtin::BI__sync_xor_and_fetch_1:
3563  case Builtin::BI__sync_xor_and_fetch_2:
3564  case Builtin::BI__sync_xor_and_fetch_4:
3565  case Builtin::BI__sync_xor_and_fetch_8:
3566  case Builtin::BI__sync_xor_and_fetch_16:
3567  BuiltinIndex = 10;
3568  break;
3569 
3570  case Builtin::BI__sync_nand_and_fetch:
3571  case Builtin::BI__sync_nand_and_fetch_1:
3572  case Builtin::BI__sync_nand_and_fetch_2:
3573  case Builtin::BI__sync_nand_and_fetch_4:
3574  case Builtin::BI__sync_nand_and_fetch_8:
3575  case Builtin::BI__sync_nand_and_fetch_16:
3576  BuiltinIndex = 11;
3577  WarnAboutSemanticsChange = true;
3578  break;
3579 
3580  case Builtin::BI__sync_val_compare_and_swap:
3581  case Builtin::BI__sync_val_compare_and_swap_1:
3582  case Builtin::BI__sync_val_compare_and_swap_2:
3583  case Builtin::BI__sync_val_compare_and_swap_4:
3584  case Builtin::BI__sync_val_compare_and_swap_8:
3585  case Builtin::BI__sync_val_compare_and_swap_16:
3586  BuiltinIndex = 12;
3587  NumFixed = 2;
3588  break;
3589 
3590  case Builtin::BI__sync_bool_compare_and_swap:
3591  case Builtin::BI__sync_bool_compare_and_swap_1:
3592  case Builtin::BI__sync_bool_compare_and_swap_2:
3593  case Builtin::BI__sync_bool_compare_and_swap_4:
3594  case Builtin::BI__sync_bool_compare_and_swap_8:
3595  case Builtin::BI__sync_bool_compare_and_swap_16:
3596  BuiltinIndex = 13;
3597  NumFixed = 2;
3598  ResultType = Context.BoolTy;
3599  break;
3600 
3601  case Builtin::BI__sync_lock_test_and_set:
3602  case Builtin::BI__sync_lock_test_and_set_1:
3603  case Builtin::BI__sync_lock_test_and_set_2:
3604  case Builtin::BI__sync_lock_test_and_set_4:
3605  case Builtin::BI__sync_lock_test_and_set_8:
3606  case Builtin::BI__sync_lock_test_and_set_16:
3607  BuiltinIndex = 14;
3608  break;
3609 
3610  case Builtin::BI__sync_lock_release:
3611  case Builtin::BI__sync_lock_release_1:
3612  case Builtin::BI__sync_lock_release_2:
3613  case Builtin::BI__sync_lock_release_4:
3614  case Builtin::BI__sync_lock_release_8:
3615  case Builtin::BI__sync_lock_release_16:
3616  BuiltinIndex = 15;
3617  NumFixed = 0;
3618  ResultType = Context.VoidTy;
3619  break;
3620 
3621  case Builtin::BI__sync_swap:
3622  case Builtin::BI__sync_swap_1:
3623  case Builtin::BI__sync_swap_2:
3624  case Builtin::BI__sync_swap_4:
3625  case Builtin::BI__sync_swap_8:
3626  case Builtin::BI__sync_swap_16:
3627  BuiltinIndex = 16;
3628  break;
3629  }
3630 
3631  // Now that we know how many fixed arguments we expect, first check that we
3632  // have at least that many.
3633  if (TheCall->getNumArgs() < 1+NumFixed) {
3634  Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3635  << 0 << 1+NumFixed << TheCall->getNumArgs()
3636  << TheCall->getCallee()->getSourceRange();
3637  return ExprError();
3638  }
3639 
3640  if (WarnAboutSemanticsChange) {
3641  Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3642  << TheCall->getCallee()->getSourceRange();
3643  }
3644 
3645  // Get the decl for the concrete builtin from this, we can tell what the
3646  // concrete integer type we should convert to is.
3647  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3648  const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3649  FunctionDecl *NewBuiltinDecl;
3650  if (NewBuiltinID == BuiltinID)
3651  NewBuiltinDecl = FDecl;
3652  else {
3653  // Perform builtin lookup to avoid redeclaring it.
3654  DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3655  LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3656  LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3657  assert(Res.getFoundDecl());
3658  NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3659  if (!NewBuiltinDecl)
3660  return ExprError();
3661  }
3662 
3663  // The first argument --- the pointer --- has a fixed type; we
3664  // deduce the types of the rest of the arguments accordingly. Walk
3665  // the remaining arguments, converting them to the deduced value type.
3666  for (unsigned i = 0; i != NumFixed; ++i) {
3667  ExprResult Arg = TheCall->getArg(i+1);
3668 
3669  // GCC does an implicit conversion to the pointer or integer ValType. This
3670  // can fail in some cases (1i -> int**), check for this error case now.
3671  // Initialize the argument.
3673  ValType, /*consume*/ false);
3674  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3675  if (Arg.isInvalid())
3676  return ExprError();
3677 
3678  // Okay, we have something that *can* be converted to the right type. Check
3679  // to see if there is a potentially weird extension going on here. This can
3680  // happen when you do an atomic operation on something like an char* and
3681  // pass in 42. The 42 gets converted to char. This is even more strange
3682  // for things like 45.123 -> char, etc.
3683  // FIXME: Do this check.
3684  TheCall->setArg(i+1, Arg.get());
3685  }
3686 
3687  ASTContext& Context = this->getASTContext();
3688 
3689  // Create a new DeclRefExpr to refer to the new decl.
3690  DeclRefExpr* NewDRE = DeclRefExpr::Create(
3691  Context,
3692  DRE->getQualifierLoc(),
3693  SourceLocation(),
3694  NewBuiltinDecl,
3695  /*enclosing*/ false,
3696  DRE->getLocation(),
3697  Context.BuiltinFnTy,
3698  DRE->getValueKind());
3699 
3700  // Set the callee in the CallExpr.
3701  // FIXME: This loses syntactic information.
3702  QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3703  ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3704  CK_BuiltinFnToFnPtr);
3705  TheCall->setCallee(PromotedCall.get());
3706 
3707  // Change the result type of the call to match the original value type. This
3708  // is arbitrary, but the codegen for these builtins ins design to handle it
3709  // gracefully.
3710  TheCall->setType(ResultType);
3711 
3712  return TheCallResult;
3713 }
3714 
3715 /// SemaBuiltinNontemporalOverloaded - We have a call to
3716 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3717 /// overloaded function based on the pointer type of its last argument.
3718 ///
3719 /// This function goes through and does final semantic checking for these
3720 /// builtins.
3721 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3722  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3723  DeclRefExpr *DRE =
3724  cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3725  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3726  unsigned BuiltinID = FDecl->getBuiltinID();
3727  assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3728  BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3729  "Unexpected nontemporal load/store builtin!");
3730  bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3731  unsigned numArgs = isStore ? 2 : 1;
3732 
3733  // Ensure that we have the proper number of arguments.
3734  if (checkArgCount(*this, TheCall, numArgs))
3735  return ExprError();
3736 
3737  // Inspect the last argument of the nontemporal builtin. This should always
3738  // be a pointer type, from which we imply the type of the memory access.
3739  // Because it is a pointer type, we don't have to worry about any implicit
3740  // casts here.
3741  Expr *PointerArg = TheCall->getArg(numArgs - 1);
3742  ExprResult PointerArgResult =
3743  DefaultFunctionArrayLvalueConversion(PointerArg);
3744 
3745  if (PointerArgResult.isInvalid())
3746  return ExprError();
3747  PointerArg = PointerArgResult.get();
3748  TheCall->setArg(numArgs - 1, PointerArg);
3749 
3750  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3751  if (!pointerType) {
3752  Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3753  << PointerArg->getType() << PointerArg->getSourceRange();
3754  return ExprError();
3755  }
3756 
3757  QualType ValType = pointerType->getPointeeType();
3758 
3759  // Strip any qualifiers off ValType.
3760  ValType = ValType.getUnqualifiedType();
3761  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3762  !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3763  !ValType->isVectorType()) {
3764  Diag(DRE->getLocStart(),
3765  diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3766  << PointerArg->getType() << PointerArg->getSourceRange();
3767  return ExprError();
3768  }
3769 
3770  if (!isStore) {
3771  TheCall->setType(ValType);
3772  return TheCallResult;
3773  }
3774 
3775  ExprResult ValArg = TheCall->getArg(0);
3777  Context, ValType, /*consume*/ false);
3778  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3779  if (ValArg.isInvalid())
3780  return ExprError();
3781 
3782  TheCall->setArg(0, ValArg.get());
3783  TheCall->setType(Context.VoidTy);
3784  return TheCallResult;
3785 }
3786 
3787 /// CheckObjCString - Checks that the argument to the builtin
3788 /// CFString constructor is correct
3789 /// Note: It might also make sense to do the UTF-16 conversion here (would
3790 /// simplify the backend).
3791 bool Sema::CheckObjCString(Expr *Arg) {
3792  Arg = Arg->IgnoreParenCasts();
3793  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3794 
3795  if (!Literal || !Literal->isAscii()) {
3796  Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3797  << Arg->getSourceRange();
3798  return true;
3799  }
3800 
3801  if (Literal->containsNonAsciiOrNull()) {
3802  StringRef String = Literal->getString();
3803  unsigned NumBytes = String.size();
3804  SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3805  const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3806  llvm::UTF16 *ToPtr = &ToBuf[0];
3807 
3808  llvm::ConversionResult Result =
3809  llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3810  ToPtr + NumBytes, llvm::strictConversion);
3811  // Check for conversion failure.
3812  if (Result != llvm::conversionOK)
3813  Diag(Arg->getLocStart(),
3814  diag::warn_cfstring_truncated) << Arg->getSourceRange();
3815  }
3816  return false;
3817 }
3818 
3819 /// CheckObjCString - Checks that the format string argument to the os_log()
3820 /// and os_trace() functions is correct, and converts it to const char *.
3821 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3822  Arg = Arg->IgnoreParenCasts();
3823  auto *Literal = dyn_cast<StringLiteral>(Arg);
3824  if (!Literal) {
3825  if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3826  Literal = ObjcLiteral->getString();
3827  }
3828  }
3829 
3830  if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3831  return ExprError(
3832  Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3833  << Arg->getSourceRange());
3834  }
3835 
3836  ExprResult Result(Literal);
3837  QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3838  InitializedEntity Entity =
3839  InitializedEntity::InitializeParameter(Context, ResultTy, false);
3840  Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3841  return Result;
3842 }
3843 
3844 /// Check that the user is calling the appropriate va_start builtin for the
3845 /// target and calling convention.
3846 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3847  const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3848  bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3849  bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3850  bool IsWindows = TT.isOSWindows();
3851  bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3852  if (IsX64 || IsAArch64) {
3853  CallingConv CC = CC_C;
3854  if (const FunctionDecl *FD = S.getCurFunctionDecl())
3855  CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3856  if (IsMSVAStart) {
3857  // Don't allow this in System V ABI functions.
3858  if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3859  return S.Diag(Fn->getLocStart(),
3860  diag::err_ms_va_start_used_in_sysv_function);
3861  } else {
3862  // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3863  // On x64 Windows, don't allow this in System V ABI functions.
3864  // (Yes, that means there's no corresponding way to support variadic
3865  // System V ABI functions on Windows.)
3866  if ((IsWindows && CC == CC_X86_64SysV) ||
3867  (!IsWindows && CC == CC_Win64))
3868  return S.Diag(Fn->getLocStart(),
3869  diag::err_va_start_used_in_wrong_abi_function)
3870  << !IsWindows;
3871  }
3872  return false;
3873  }
3874 
3875  if (IsMSVAStart)
3876  return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3877  return false;
3878 }
3879 
3881  ParmVarDecl **LastParam = nullptr) {
3882  // Determine whether the current function, block, or obj-c method is variadic
3883  // and get its parameter list.
3884  bool IsVariadic = false;
3885  ArrayRef<ParmVarDecl *> Params;
3886  DeclContext *Caller = S.CurContext;
3887  if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3888  IsVariadic = Block->isVariadic();
3889  Params = Block->parameters();
3890  } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3891  IsVariadic = FD->isVariadic();
3892  Params = FD->parameters();
3893  } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3894  IsVariadic = MD->isVariadic();
3895  // FIXME: This isn't correct for methods (results in bogus warning).
3896  Params = MD->parameters();
3897  } else if (isa<CapturedDecl>(Caller)) {
3898  // We don't support va_start in a CapturedDecl.
3899  S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3900  return true;
3901  } else {
3902  // This must be some other declcontext that parses exprs.
3903  S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3904  return true;
3905  }
3906 
3907  if (!IsVariadic) {
3908  S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3909  return true;
3910  }
3911 
3912  if (LastParam)
3913  *LastParam = Params.empty() ? nullptr : Params.back();
3914 
3915  return false;
3916 }
3917 
3918 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3919 /// for validity. Emit an error and return true on failure; return false
3920 /// on success.
3921 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3922  Expr *Fn = TheCall->getCallee();
3923 
3924  if (checkVAStartABI(*this, BuiltinID, Fn))
3925  return true;
3926 
3927  if (TheCall->getNumArgs() > 2) {
3928  Diag(TheCall->getArg(2)->getLocStart(),
3929  diag::err_typecheck_call_too_many_args)
3930  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3931  << Fn->getSourceRange()
3932  << SourceRange(TheCall->getArg(2)->getLocStart(),
3933  (*(TheCall->arg_end()-1))->getLocEnd());
3934  return true;
3935  }
3936 
3937  if (TheCall->getNumArgs() < 2) {
3938  return Diag(TheCall->getLocEnd(),
3939  diag::err_typecheck_call_too_few_args_at_least)
3940  << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3941  }
3942 
3943  // Type-check the first argument normally.
3944  if (checkBuiltinArgument(*this, TheCall, 0))
3945  return true;
3946 
3947  // Check that the current function is variadic, and get its last parameter.
3948  ParmVarDecl *LastParam;
3949  if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3950  return true;
3951 
3952  // Verify that the second argument to the builtin is the last argument of the
3953  // current function or method.
3954  bool SecondArgIsLastNamedArgument = false;
3955  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3956 
3957  // These are valid if SecondArgIsLastNamedArgument is false after the next
3958  // block.
3959  QualType Type;
3960  SourceLocation ParamLoc;
3961  bool IsCRegister = false;
3962 
3963  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3964  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3965  SecondArgIsLastNamedArgument = PV == LastParam;
3966 
3967  Type = PV->getType();
3968  ParamLoc = PV->getLocation();
3969  IsCRegister =
3970  PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3971  }
3972  }
3973 
3974  if (!SecondArgIsLastNamedArgument)
3975  Diag(TheCall->getArg(1)->getLocStart(),
3976  diag::warn_second_arg_of_va_start_not_last_named_param);
3977  else if (IsCRegister || Type->isReferenceType() ||
3978  Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3979  // Promotable integers are UB, but enumerations need a bit of
3980  // extra checking to see what their promotable type actually is.
3981  if (!Type->isPromotableIntegerType())
3982  return false;
3983  if (!Type->isEnumeralType())
3984  return true;
3985  const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3986  return !(ED &&
3987  Context.typesAreCompatible(ED->getPromotionType(), Type));
3988  }()) {
3989  unsigned Reason = 0;
3990  if (Type->isReferenceType()) Reason = 1;
3991  else if (IsCRegister) Reason = 2;
3992  Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3993  Diag(ParamLoc, diag::note_parameter_type) << Type;
3994  }
3995 
3996  TheCall->setType(Context.VoidTy);
3997  return false;
3998 }
3999 
4000 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4001  // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4002  // const char *named_addr);
4003 
4004  Expr *Func = Call->getCallee();
4005 
4006  if (Call->getNumArgs() < 3)
4007  return Diag(Call->getLocEnd(),
4008  diag::err_typecheck_call_too_few_args_at_least)
4009  << 0 /*function call*/ << 3 << Call->getNumArgs();
4010 
4011  // Type-check the first argument normally.
4012  if (checkBuiltinArgument(*this, Call, 0))
4013  return true;
4014 
4015  // Check that the current function is variadic.
4016  if (checkVAStartIsInVariadicFunction(*this, Func))
4017  return true;
4018 
4019  // __va_start on Windows does not validate the parameter qualifiers
4020 
4021  const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4022  const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4023 
4024  const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4025  const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4026 
4027  const QualType &ConstCharPtrTy =
4028  Context.getPointerType(Context.CharTy.withConst());
4029  if (!Arg1Ty->isPointerType() ||
4030  Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4031  Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4032  << Arg1->getType() << ConstCharPtrTy
4033  << 1 /* different class */
4034  << 0 /* qualifier difference */
4035  << 3 /* parameter mismatch */
4036  << 2 << Arg1->getType() << ConstCharPtrTy;
4037 
4038  const QualType SizeTy = Context.getSizeType();
4039  if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4040  Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4041  << Arg2->getType() << SizeTy
4042  << 1 /* different class */
4043  << 0 /* qualifier difference */
4044  << 3 /* parameter mismatch */
4045  << 3 << Arg2->getType() << SizeTy;
4046 
4047  return false;
4048 }
4049 
4050 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4051 /// friends. This is declared to take (...), so we have to check everything.
4052 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4053  if (TheCall->getNumArgs() < 2)
4054  return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4055  << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4056  if (TheCall->getNumArgs() > 2)
4057  return Diag(TheCall->getArg(2)->getLocStart(),
4058  diag::err_typecheck_call_too_many_args)
4059  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4060  << SourceRange(TheCall->getArg(2)->getLocStart(),
4061  (*(TheCall->arg_end()-1))->getLocEnd());
4062 
4063  ExprResult OrigArg0 = TheCall->getArg(0);
4064  ExprResult OrigArg1 = TheCall->getArg(1);
4065 
4066  // Do standard promotions between the two arguments, returning their common
4067  // type.
4068  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4069  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4070  return true;
4071 
4072  // Make sure any conversions are pushed back into the call; this is
4073  // type safe since unordered compare builtins are declared as "_Bool
4074  // foo(...)".
4075  TheCall->setArg(0, OrigArg0.get());
4076  TheCall->setArg(1, OrigArg1.get());
4077 
4078  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4079  return false;
4080 
4081  // If the common type isn't a real floating type, then the arguments were
4082  // invalid for this operation.
4083  if (Res.isNull() || !Res->isRealFloatingType())
4084  return Diag(OrigArg0.get()->getLocStart(),
4085  diag::err_typecheck_call_invalid_ordered_compare)
4086  << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4087  << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4088 
4089  return false;
4090 }
4091 
4092 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4093 /// __builtin_isnan and friends. This is declared to take (...), so we have
4094 /// to check everything. We expect the last argument to be a floating point
4095 /// value.
4096 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4097  if (TheCall->getNumArgs() < NumArgs)
4098  return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4099  << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4100  if (TheCall->getNumArgs() > NumArgs)
4101  return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4102  diag::err_typecheck_call_too_many_args)
4103  << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4104  << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4105  (*(TheCall->arg_end()-1))->getLocEnd());
4106 
4107  Expr *OrigArg = TheCall->getArg(NumArgs-1);
4108 
4109  if (OrigArg->isTypeDependent())
4110  return false;
4111 
4112  // This operation requires a non-_Complex floating-point number.
4113  if (!OrigArg->getType()->isRealFloatingType())
4114  return Diag(OrigArg->getLocStart(),
4115  diag::err_typecheck_call_invalid_unary_fp)
4116  << OrigArg->getType() << OrigArg->getSourceRange();
4117 
4118  // If this is an implicit conversion from float -> float or double, remove it.
4119  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4120  // Only remove standard FloatCasts, leaving other casts inplace
4121  if (Cast->getCastKind() == CK_FloatingCast) {
4122  Expr *CastArg = Cast->getSubExpr();
4123  if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4124  assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4125  Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4126  "promotion from float to either float or double is the only expected cast here");
4127  Cast->setSubExpr(nullptr);
4128  TheCall->setArg(NumArgs-1, CastArg);
4129  }
4130  }
4131  }
4132 
4133  return false;
4134 }
4135 
4136 // Customized Sema Checking for VSX builtins that have the following signature:
4137 // vector [...] builtinName(vector [...], vector [...], const int);
4138 // Which takes the same type of vectors (any legal vector type) for the first
4139 // two arguments and takes compile time constant for the third argument.
4140 // Example builtins are :
4141 // vector double vec_xxpermdi(vector double, vector double, int);
4142 // vector short vec_xxsldwi(vector short, vector short, int);
4143 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4144  unsigned ExpectedNumArgs = 3;
4145  if (TheCall->getNumArgs() < ExpectedNumArgs)
4146  return Diag(TheCall->getLocEnd(),
4147  diag::err_typecheck_call_too_few_args_at_least)
4148  << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4149  << TheCall->getSourceRange();
4150 
4151  if (TheCall->getNumArgs() > ExpectedNumArgs)
4152  return Diag(TheCall->getLocEnd(),
4153  diag::err_typecheck_call_too_many_args_at_most)
4154  << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4155  << TheCall->getSourceRange();
4156 
4157  // Check the third argument is a compile time constant
4158  llvm::APSInt Value;
4159  if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4160  return Diag(TheCall->getLocStart(),
4161  diag::err_vsx_builtin_nonconstant_argument)
4162  << 3 /* argument index */ << TheCall->getDirectCallee()
4163  << SourceRange(TheCall->getArg(2)->getLocStart(),
4164  TheCall->getArg(2)->getLocEnd());
4165 
4166  QualType Arg1Ty = TheCall->getArg(0)->getType();
4167  QualType Arg2Ty = TheCall->getArg(1)->getType();
4168 
4169  // Check the type of argument 1 and argument 2 are vectors.
4170  SourceLocation BuiltinLoc = TheCall->getLocStart();
4171  if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4172  (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4173  return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4174  << TheCall->getDirectCallee()
4175  << SourceRange(TheCall->getArg(0)->getLocStart(),
4176  TheCall->getArg(1)->getLocEnd());
4177  }
4178 
4179  // Check the first two arguments are the same type.
4180  if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4181  return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4182  << TheCall->getDirectCallee()
4183  << SourceRange(TheCall->getArg(0)->getLocStart(),
4184  TheCall->getArg(1)->getLocEnd());
4185  }
4186 
4187  // When default clang type checking is turned off and the customized type
4188  // checking is used, the returning type of the function must be explicitly
4189  // set. Otherwise it is _Bool by default.
4190  TheCall->setType(Arg1Ty);
4191 
4192  return false;
4193 }
4194 
4195 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4196 // This is declared to take (...), so we have to check everything.
4198  if (TheCall->getNumArgs() < 2)
4199  return ExprError(Diag(TheCall->getLocEnd(),
4200  diag::err_typecheck_call_too_few_args_at_least)
4201  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4202  << TheCall->getSourceRange());
4203 
4204  // Determine which of the following types of shufflevector we're checking:
4205  // 1) unary, vector mask: (lhs, mask)
4206  // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4207  QualType resType = TheCall->getArg(0)->getType();
4208  unsigned numElements = 0;
4209 
4210  if (!TheCall->getArg(0)->isTypeDependent() &&
4211  !TheCall->getArg(1)->isTypeDependent()) {
4212  QualType LHSType = TheCall->getArg(0)->getType();
4213  QualType RHSType = TheCall->getArg(1)->getType();
4214 
4215  if (!LHSType->isVectorType() || !RHSType->isVectorType())
4216  return ExprError(Diag(TheCall->getLocStart(),
4217  diag::err_vec_builtin_non_vector)
4218  << TheCall->getDirectCallee()
4219  << SourceRange(TheCall->getArg(0)->getLocStart(),
4220  TheCall->getArg(1)->getLocEnd()));
4221 
4222  numElements = LHSType->getAs<VectorType>()->getNumElements();
4223  unsigned numResElements = TheCall->getNumArgs() - 2;
4224 
4225  // Check to see if we have a call with 2 vector arguments, the unary shuffle
4226  // with mask. If so, verify that RHS is an integer vector type with the
4227  // same number of elts as lhs.
4228  if (TheCall->getNumArgs() == 2) {
4229  if (!RHSType->hasIntegerRepresentation() ||
4230  RHSType->getAs<VectorType>()->getNumElements() != numElements)
4231  return ExprError(Diag(TheCall->getLocStart(),
4232  diag::err_vec_builtin_incompatible_vector)
4233  << TheCall->getDirectCallee()
4234  << SourceRange(TheCall->getArg(1)->getLocStart(),
4235  TheCall->getArg(1)->getLocEnd()));
4236  } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4237  return ExprError(Diag(TheCall->getLocStart(),
4238  diag::err_vec_builtin_incompatible_vector)
4239  << TheCall->getDirectCallee()
4240  << SourceRange(TheCall->getArg(0)->getLocStart(),
4241  TheCall->getArg(1)->getLocEnd()));
4242  } else if (numElements != numResElements) {
4243  QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4244  resType = Context.getVectorType(eltType, numResElements,
4246  }
4247  }
4248 
4249  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4250  if (TheCall->getArg(i)->isTypeDependent() ||
4251  TheCall->getArg(i)->isValueDependent())
4252  continue;
4253 
4254  llvm::APSInt Result(32);
4255  if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4256  return ExprError(Diag(TheCall->getLocStart(),
4257  diag::err_shufflevector_nonconstant_argument)
4258  << TheCall->getArg(i)->getSourceRange());
4259 
4260  // Allow -1 which will be translated to undef in the IR.
4261  if (Result.isSigned() && Result.isAllOnesValue())
4262  continue;
4263 
4264  if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4265  return ExprError(Diag(TheCall->getLocStart(),
4266  diag::err_shufflevector_argument_too_large)
4267  << TheCall->getArg(i)->getSourceRange());
4268  }
4269 
4270  SmallVector<Expr*, 32> exprs;
4271 
4272  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4273  exprs.push_back(TheCall->getArg(i));
4274  TheCall->setArg(i, nullptr);
4275  }
4276 
4277  return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4278  TheCall->getCallee()->getLocStart(),
4279  TheCall->getRParenLoc());
4280 }
4281 
4282 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4284  SourceLocation BuiltinLoc,
4285  SourceLocation RParenLoc) {
4286  ExprValueKind VK = VK_RValue;
4288  QualType DstTy = TInfo->getType();
4289  QualType SrcTy = E->getType();
4290 
4291  if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4292  return ExprError(Diag(BuiltinLoc,
4293  diag::err_convertvector_non_vector)
4294  << E->getSourceRange());
4295  if (!DstTy->isVectorType() && !DstTy->isDependentType())
4296  return ExprError(Diag(BuiltinLoc,
4297  diag::err_convertvector_non_vector_type));
4298 
4299  if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4300  unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4301  unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4302  if (SrcElts != DstElts)
4303  return ExprError(Diag(BuiltinLoc,
4304  diag::err_convertvector_incompatible_vector)
4305  << E->getSourceRange());
4306  }
4307 
4308  return new (Context)
4309  ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4310 }
4311 
4312 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4313 // This is declared to take (const void*, ...) and can take two
4314 // optional constant int args.
4315 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4316  unsigned NumArgs = TheCall->getNumArgs();
4317 
4318  if (NumArgs > 3)
4319  return Diag(TheCall->getLocEnd(),
4320  diag::err_typecheck_call_too_many_args_at_most)
4321  << 0 /*function call*/ << 3 << NumArgs
4322  << TheCall->getSourceRange();
4323 
4324  // Argument 0 is checked for us and the remaining arguments must be
4325  // constant integers.
4326  for (unsigned i = 1; i != NumArgs; ++i)
4327  if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4328  return true;
4329 
4330  return false;
4331 }
4332 
4333 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4334 // __assume does not evaluate its arguments, and should warn if its argument
4335 // has side effects.
4336 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4337  Expr *Arg = TheCall->getArg(0);
4338  if (Arg->isInstantiationDependent()) return false;
4339 
4340  if (Arg->HasSideEffects(Context))
4341  Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4342  << Arg->getSourceRange()
4343  << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4344 
4345  return false;
4346 }
4347 
4348 /// Handle __builtin_alloca_with_align. This is declared
4349 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4350 /// than 8.
4351 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4352  // The alignment must be a constant integer.
4353  Expr *Arg = TheCall->getArg(1);
4354 
4355  // We can't check the value of a dependent argument.
4356  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4357  if (const auto *UE =
4358  dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4359  if (UE->getKind() == UETT_AlignOf)
4360  Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4361  << Arg->getSourceRange();
4362 
4363  llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4364 
4365  if (!Result.isPowerOf2())
4366  return Diag(TheCall->getLocStart(),
4367  diag::err_alignment_not_power_of_two)
4368  << Arg->getSourceRange();
4369 
4370  if (Result < Context.getCharWidth())
4371  return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4372  << (unsigned)Context.getCharWidth()
4373  << Arg->getSourceRange();
4374 
4375  if (Result > std::numeric_limits<int32_t>::max())
4376  return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4378  << Arg->getSourceRange();
4379  }
4380 
4381  return false;
4382 }
4383 
4384 /// Handle __builtin_assume_aligned. This is declared
4385 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4386 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4387  unsigned NumArgs = TheCall->getNumArgs();
4388 
4389  if (NumArgs > 3)
4390  return Diag(TheCall->getLocEnd(),
4391  diag::err_typecheck_call_too_many_args_at_most)
4392  << 0 /*function call*/ << 3 << NumArgs
4393  << TheCall->getSourceRange();
4394 
4395  // The alignment must be a constant integer.
4396  Expr *Arg = TheCall->getArg(1);
4397 
4398  // We can't check the value of a dependent argument.
4399  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4400  llvm::APSInt Result;
4401  if (SemaBuiltinConstantArg(TheCall, 1, Result))
4402  return true;
4403 
4404  if (!Result.isPowerOf2())
4405  return Diag(TheCall->getLocStart(),
4406  diag::err_alignment_not_power_of_two)
4407  << Arg->getSourceRange();
4408  }
4409 
4410  if (NumArgs > 2) {
4411  ExprResult Arg(TheCall->getArg(2));
4413  Context.getSizeType(), false);
4414  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4415  if (Arg.isInvalid()) return true;
4416  TheCall->setArg(2, Arg.get());
4417  }
4418 
4419  return false;
4420 }
4421 
4422 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4423  unsigned BuiltinID =
4424  cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4425  bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4426 
4427  unsigned NumArgs = TheCall->getNumArgs();
4428  unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4429  if (NumArgs < NumRequiredArgs) {
4430  return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4431  << 0 /* function call */ << NumRequiredArgs << NumArgs
4432  << TheCall->getSourceRange();
4433  }
4434  if (NumArgs >= NumRequiredArgs + 0x100) {
4435  return Diag(TheCall->getLocEnd(),
4436  diag::err_typecheck_call_too_many_args_at_most)
4437  << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4438  << TheCall->getSourceRange();
4439  }
4440  unsigned i = 0;
4441 
4442  // For formatting call, check buffer arg.
4443  if (!IsSizeCall) {
4444  ExprResult Arg(TheCall->getArg(i));
4446  Context, Context.VoidPtrTy, false);
4447  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4448  if (Arg.isInvalid())
4449  return true;
4450  TheCall->setArg(i, Arg.get());
4451  i++;
4452  }
4453 
4454  // Check string literal arg.
4455  unsigned FormatIdx = i;
4456  {
4457  ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4458  if (Arg.isInvalid())
4459  return true;
4460  TheCall->setArg(i, Arg.get());
4461  i++;
4462  }
4463 
4464  // Make sure variadic args are scalar.
4465  unsigned FirstDataArg = i;
4466  while (i < NumArgs) {
4467  ExprResult Arg = DefaultVariadicArgumentPromotion(
4468  TheCall->getArg(i), VariadicFunction, nullptr);
4469  if (Arg.isInvalid())
4470  return true;
4471  CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4472  if (ArgSize.getQuantity() >= 0x100) {
4473  return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4474  << i << (int)ArgSize.getQuantity() << 0xff
4475  << TheCall->getSourceRange();
4476  }
4477  TheCall->setArg(i, Arg.get());
4478  i++;
4479  }
4480 
4481  // Check formatting specifiers. NOTE: We're only doing this for the non-size
4482  // call to avoid duplicate diagnostics.
4483  if (!IsSizeCall) {
4484  llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4485  ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4486  bool Success = CheckFormatArguments(
4487  Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4488  VariadicFunction, TheCall->getLocStart(), SourceRange(),
4489  CheckedVarArgs);
4490  if (!Success)
4491  return true;
4492  }
4493 
4494  if (IsSizeCall) {
4495  TheCall->setType(Context.getSizeType());
4496  } else {
4497  TheCall->setType(Context.VoidPtrTy);
4498  }
4499  return false;
4500 }
4501 
4502 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4503 /// TheCall is a constant expression.
4504 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4505  llvm::APSInt &Result) {
4506  Expr *Arg = TheCall->getArg(ArgNum);
4507  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4508  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4509 
4510  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4511 
4512  if (!Arg->isIntegerConstantExpr(Result, Context))
4513  return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4514  << FDecl->getDeclName() << Arg->getSourceRange();
4515 
4516  return false;
4517 }
4518 
4519 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4520 /// TheCall is a constant expression in the range [Low, High].
4521 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4522  int Low, int High) {
4523  llvm::APSInt Result;
4524 
4525  // We can't check the value of a dependent argument.
4526  Expr *Arg = TheCall->getArg(ArgNum);
4527  if (Arg->isTypeDependent() || Arg->isValueDependent())
4528  return false;
4529 
4530  // Check constant-ness first.
4531  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4532  return true;
4533 
4534  if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4535  return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4536  << Low << High << Arg->getSourceRange();
4537 
4538  return false;
4539 }
4540 
4541 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4542 /// TheCall is a constant expression is a multiple of Num..
4543 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4544  unsigned Num) {
4545  llvm::APSInt Result;
4546 
4547  // We can't check the value of a dependent argument.
4548  Expr *Arg = TheCall->getArg(ArgNum);
4549  if (Arg->isTypeDependent() || Arg->isValueDependent())
4550  return false;
4551 
4552  // Check constant-ness first.
4553  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4554  return true;
4555 
4556  if (Result.getSExtValue() % Num != 0)
4557  return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4558  << Num << Arg->getSourceRange();
4559 
4560  return false;
4561 }
4562 
4563 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4564 /// TheCall is an ARM/AArch64 special register string literal.
4565 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4566  int ArgNum, unsigned ExpectedFieldNum,
4567  bool AllowName) {
4568  bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4569  BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4570  BuiltinID == ARM::BI__builtin_arm_rsr ||
4571  BuiltinID == ARM::BI__builtin_arm_rsrp ||
4572  BuiltinID == ARM::BI__builtin_arm_wsr ||
4573  BuiltinID == ARM::BI__builtin_arm_wsrp;
4574  bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4575  BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4576  BuiltinID == AArch64::BI__builtin_arm_rsr ||
4577  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4578  BuiltinID == AArch64::BI__builtin_arm_wsr ||
4579  BuiltinID == AArch64::BI__builtin_arm_wsrp;
4580  assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4581 
4582  // We can't check the value of a dependent argument.
4583  Expr *Arg = TheCall->getArg(ArgNum);
4584  if (Arg->isTypeDependent() || Arg->isValueDependent())
4585  return false;
4586 
4587  // Check if the argument is a string literal.
4588  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4589  return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4590  << Arg->getSourceRange();
4591 
4592  // Check the type of special register given.
4593  StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4595  Reg.split(Fields, ":");
4596 
4597  if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4598  return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4599  << Arg->getSourceRange();
4600 
4601  // If the string is the name of a register then we cannot check that it is
4602  // valid here but if the string is of one the forms described in ACLE then we
4603  // can check that the supplied fields are integers and within the valid
4604  // ranges.
4605  if (Fields.size() > 1) {
4606  bool FiveFields = Fields.size() == 5;
4607 
4608  bool ValidString = true;
4609  if (IsARMBuiltin) {
4610  ValidString &= Fields[0].startswith_lower("cp") ||
4611  Fields[0].startswith_lower("p");
4612  if (ValidString)
4613  Fields[0] =
4614  Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4615 
4616  ValidString &= Fields[2].startswith_lower("c");
4617  if (ValidString)
4618  Fields[2] = Fields[2].drop_front(1);
4619 
4620  if (FiveFields) {
4621  ValidString &= Fields[3].startswith_lower("c");
4622  if (ValidString)
4623  Fields[3] = Fields[3].drop_front(1);
4624  }
4625  }
4626 
4627  SmallVector<int, 5> Ranges;
4628  if (FiveFields)
4629  Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4630  else
4631  Ranges.append({15, 7, 15});
4632 
4633  for (unsigned i=0; i<Fields.size(); ++i) {
4634  int IntField;
4635  ValidString &= !Fields[i].getAsInteger(10, IntField);
4636  ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4637  }
4638 
4639  if (!ValidString)
4640  return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4641  << Arg->getSourceRange();
4642  } else if (IsAArch64Builtin && Fields.size() == 1) {
4643  // If the register name is one of those that appear in the condition below
4644  // and the special register builtin being used is one of the write builtins,
4645  // then we require that the argument provided for writing to the register
4646  // is an integer constant expression. This is because it will be lowered to
4647  // an MSR (immediate) instruction, so we need to know the immediate at
4648  // compile time.
4649  if (TheCall->getNumArgs() != 2)
4650  return false;
4651 
4652  std::string RegLower = Reg.lower();
4653  if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4654  RegLower != "pan" && RegLower != "uao")
4655  return false;
4656 
4657  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4658  }
4659 
4660  return false;
4661 }
4662 
4663 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4664 /// This checks that the target supports __builtin_longjmp and
4665 /// that val is a constant 1.
4666 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4667  if (!Context.getTargetInfo().hasSjLjLowering())
4668  return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4669  << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4670 
4671  Expr *Arg = TheCall->getArg(1);
4672  llvm::APSInt Result;
4673 
4674  // TODO: This is less than ideal. Overload this to take a value.
4675  if (SemaBuiltinConstantArg(TheCall, 1, Result))
4676  return true;
4677 
4678  if (Result != 1)
4679  return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4680  << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4681 
4682  return false;
4683 }
4684 
4685 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4686 /// This checks that the target supports __builtin_setjmp.
4687 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4688  if (!Context.getTargetInfo().hasSjLjLowering())
4689  return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4690  << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4691  return false;
4692 }
4693 
4694 namespace {
4695 
4696 class UncoveredArgHandler {
4697  enum { Unknown = -1, AllCovered = -2 };
4698 
4699  signed FirstUncoveredArg = Unknown;
4700  SmallVector<const Expr *, 4> DiagnosticExprs;
4701 
4702 public:
4703  UncoveredArgHandler() = default;
4704 
4705  bool hasUncoveredArg() const {
4706  return (FirstUncoveredArg >= 0);
4707  }
4708 
4709  unsigned getUncoveredArg() const {
4710  assert(hasUncoveredArg() && "no uncovered argument");
4711  return FirstUncoveredArg;
4712  }
4713 
4714  void setAllCovered() {
4715  // A string has been found with all arguments covered, so clear out
4716  // the diagnostics.
4717  DiagnosticExprs.clear();
4718  FirstUncoveredArg = AllCovered;
4719  }
4720 
4721  void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4722  assert(NewFirstUncoveredArg >= 0 && "Outside range");
4723 
4724  // Don't update if a previous string covers all arguments.
4725  if (FirstUncoveredArg == AllCovered)
4726  return;
4727 
4728  // UncoveredArgHandler tracks the highest uncovered argument index
4729  // and with it all the strings that match this index.
4730  if (NewFirstUncoveredArg == FirstUncoveredArg)
4731  DiagnosticExprs.push_back(StrExpr);
4732  else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4733  DiagnosticExprs.clear();
4734  DiagnosticExprs.push_back(StrExpr);
4735  FirstUncoveredArg = NewFirstUncoveredArg;
4736  }
4737  }
4738 
4739  void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4740 };
4741 
4743  SLCT_NotALiteral,
4744  SLCT_UncheckedLiteral,
4745  SLCT_CheckedLiteral
4746 };
4747 
4748 } // namespace
4749 
4750 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4751  BinaryOperatorKind BinOpKind,
4752  bool AddendIsRight) {
4753  unsigned BitWidth = Offset.getBitWidth();
4754  unsigned AddendBitWidth = Addend.getBitWidth();
4755  // There might be negative interim results.
4756  if (Addend.isUnsigned()) {
4757  Addend = Addend.zext(++AddendBitWidth);
4758  Addend.setIsSigned(true);
4759  }
4760  // Adjust the bit width of the APSInts.
4761  if (AddendBitWidth > BitWidth) {
4762  Offset = Offset.sext(AddendBitWidth);
4763  BitWidth = AddendBitWidth;
4764  } else if (BitWidth > AddendBitWidth) {
4765  Addend = Addend.sext(BitWidth);
4766  }
4767 
4768  bool Ov = false;
4769  llvm::APSInt ResOffset = Offset;
4770  if (BinOpKind == BO_Add)
4771  ResOffset = Offset.sadd_ov(Addend, Ov);
4772  else {
4773  assert(AddendIsRight && BinOpKind == BO_Sub &&
4774  "operator must be add or sub with addend on the right");
4775  ResOffset = Offset.ssub_ov(Addend, Ov);
4776  }
4777 
4778  // We add an offset to a pointer here so we should support an offset as big as
4779  // possible.
4780  if (Ov) {
4781  assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4782  "index (intermediate) result too big");
4783  Offset = Offset.sext(2 * BitWidth);
4784  sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4785  return;
4786  }
4787 
4788  Offset = ResOffset;
4789 }
4790 
4791 namespace {
4792 
4793 // This is a wrapper class around StringLiteral to support offsetted string
4794 // literals as format strings. It takes the offset into account when returning
4795 // the string and its length or the source locations to display notes correctly.
4796 class FormatStringLiteral {
4797  const StringLiteral *FExpr;
4798  int64_t Offset;
4799 
4800  public:
4801  FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4802  : FExpr(fexpr), Offset(Offset) {}
4803 
4804  StringRef getString() const {
4805  return FExpr->getString().drop_front(Offset);
4806  }
4807 
4808  unsigned getByteLength() const {
4809  return FExpr->getByteLength() - getCharByteWidth() * Offset;
4810  }
4811 
4812  unsigned getLength() const { return FExpr->getLength() - Offset; }
4813  unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4814 
4815  StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4816 
4817  QualType getType() const { return FExpr->getType(); }
4818 
4819  bool isAscii() const { return FExpr->isAscii(); }
4820  bool isWide() const { return FExpr->isWide(); }
4821  bool isUTF8() const { return FExpr->isUTF8(); }
4822  bool isUTF16() const { return FExpr->isUTF16(); }
4823  bool isUTF32() const { return FExpr->isUTF32(); }
4824  bool isPascal() const { return FExpr->isPascal(); }
4825 
4826  SourceLocation getLocationOfByte(
4827  unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4828  const TargetInfo &Target, unsigned *StartToken = nullptr,
4829  unsigned *StartTokenByteOffset = nullptr) const {
4830  return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4831  StartToken, StartTokenByteOffset);
4832  }
4833 
4834  SourceLocation getLocStart() const LLVM_READONLY {
4835  return FExpr->getLocStart().getLocWithOffset(Offset);
4836  }
4837 
4838  SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4839 };
4840 
4841 } // namespace
4842 
4843 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4844  const Expr *OrigFormatExpr,
4845  ArrayRef<const Expr *> Args,
4846  bool HasVAListArg, unsigned format_idx,
4847  unsigned firstDataArg,
4849  bool inFunctionCall,
4850  Sema::VariadicCallType CallType,
4851  llvm::SmallBitVector &CheckedVarArgs,
4852  UncoveredArgHandler &UncoveredArg);
4853 
4854 // Determine if an expression is a string literal or constant string.
4855 // If this function returns false on the arguments to a function expecting a
4856 // format string, we will usually need to emit a warning.
4857 // True string literals are then checked by CheckFormatString.
4859 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4860  bool HasVAListArg, unsigned format_idx,
4861  unsigned firstDataArg, Sema::FormatStringType Type,
4862  Sema::VariadicCallType CallType, bool InFunctionCall,
4863  llvm::SmallBitVector &CheckedVarArgs,
4864  UncoveredArgHandler &UncoveredArg,
4865  llvm::APSInt Offset) {
4866  tryAgain:
4867  assert(Offset.isSigned() && "invalid offset");
4868 
4869  if (E->isTypeDependent() || E->isValueDependent())
4870  return SLCT_NotALiteral;
4871 
4872  E = E->IgnoreParenCasts();
4873 
4875  // Technically -Wformat-nonliteral does not warn about this case.
4876  // The behavior of printf and friends in this case is implementation
4877  // dependent. Ideally if the format string cannot be null then
4878  // it should have a 'nonnull' attribute in the function prototype.
4879  return SLCT_UncheckedLiteral;
4880 
4881  switch (E->getStmtClass()) {
4882  case Stmt::BinaryConditionalOperatorClass:
4883  case Stmt::ConditionalOperatorClass: {
4884  // The expression is a literal if both sub-expressions were, and it was
4885  // completely checked only if both sub-expressions were checked.
4886  const AbstractConditionalOperator *C =
4887  cast<AbstractConditionalOperator>(E);
4888 
4889  // Determine whether it is necessary to check both sub-expressions, for
4890  // example, because the condition expression is a constant that can be
4891  // evaluated at compile time.
4892  bool CheckLeft = true, CheckRight = true;
4893 
4894  bool Cond;
4895  if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4896  if (Cond)
4897  CheckRight = false;
4898  else
4899  CheckLeft = false;
4900  }
4901 
4902  // We need to maintain the offsets for the right and the left hand side
4903  // separately to check if every possible indexed expression is a valid
4904  // string literal. They might have different offsets for different string
4905  // literals in the end.
4907  if (!CheckLeft)
4908  Left = SLCT_UncheckedLiteral;
4909  else {
4910  Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4911  HasVAListArg, format_idx, firstDataArg,
4912  Type, CallType, InFunctionCall,
4913  CheckedVarArgs, UncoveredArg, Offset);
4914  if (Left == SLCT_NotALiteral || !CheckRight) {
4915  return Left;
4916  }
4917  }
4918 
4919  StringLiteralCheckType Right =
4920  checkFormatStringExpr(S, C->getFalseExpr(), Args,
4921  HasVAListArg, format_idx, firstDataArg,
4922  Type, CallType, InFunctionCall, CheckedVarArgs,
4923  UncoveredArg, Offset);
4924 
4925  return (CheckLeft && Left < Right) ? Left : Right;
4926  }
4927 
4928  case Stmt::ImplicitCastExprClass:
4929  E = cast<ImplicitCastExpr>(E)->getSubExpr();
4930  goto tryAgain;
4931 
4932  case Stmt::OpaqueValueExprClass:
4933  if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4934  E = src;
4935  goto tryAgain;
4936  }
4937  return SLCT_NotALiteral;
4938 
4939  case Stmt::PredefinedExprClass:
4940  // While __func__, etc., are technically not string literals, they
4941  // cannot contain format specifiers and thus are not a security
4942  // liability.
4943  return SLCT_UncheckedLiteral;
4944 
4945  case Stmt::DeclRefExprClass: {
4946  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4947 
4948  // As an exception, do not flag errors for variables binding to
4949  // const string literals.
4950  if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4951  bool isConstant = false;
4952  QualType T = DR->getType();
4953 
4954  if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4955  isConstant = AT->getElementType().isConstant(S.Context);
4956  } else if (const PointerType *PT = T->getAs<PointerType>()) {
4957  isConstant = T.isConstant(S.Context) &&
4958  PT->getPointeeType().isConstant(S.Context);
4959  } else if (T->isObjCObjectPointerType()) {
4960  // In ObjC, there is usually no "const ObjectPointer" type,
4961  // so don't check if the pointee type is constant.
4962  isConstant = T.isConstant(S.Context);
4963  }
4964 
4965  if (isConstant) {
4966  if (const Expr *Init = VD->getAnyInitializer()) {
4967  // Look through initializers like const char c[] = { "foo" }
4968  if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4969  if (InitList->isStringLiteralInit())
4970  Init = InitList->getInit(0)->IgnoreParenImpCasts();
4971  }
4972  return checkFormatStringExpr(S, Init, Args,
4973  HasVAListArg, format_idx,
4974  firstDataArg, Type, CallType,
4975  /*InFunctionCall*/ false, CheckedVarArgs,
4976  UncoveredArg, Offset);
4977  }
4978  }
4979 
4980  // For vprintf* functions (i.e., HasVAListArg==true), we add a
4981  // special check to see if the format string is a function parameter
4982  // of the function calling the printf function. If the function
4983  // has an attribute indicating it is a printf-like function, then we
4984  // should suppress warnings concerning non-literals being used in a call
4985  // to a vprintf function. For example:
4986  //
4987  // void
4988  // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4989  // va_list ap;
4990  // va_start(ap, fmt);
4991  // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4992  // ...
4993  // }
4994  if (HasVAListArg) {
4995  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4996  if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4997  int PVIndex = PV->getFunctionScopeIndex() + 1;
4998  for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4999  // adjust for implicit parameter
5000  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5001  if (MD->isInstance())
5002  ++PVIndex;
5003  // We also check if the formats are compatible.
5004  // We can't pass a 'scanf' string to a 'printf' function.
5005  if (PVIndex == PVFormat->getFormatIdx() &&
5006  Type == S.GetFormatStringType(PVFormat))
5007  return SLCT_UncheckedLiteral;
5008  }
5009  }
5010  }
5011  }
5012  }
5013 
5014  return SLCT_NotALiteral;
5015  }
5016 
5017  case Stmt::CallExprClass:
5018  case Stmt::CXXMemberCallExprClass: {
5019  const CallExpr *CE = cast<CallExpr>(E);
5020  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5021  if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5022  unsigned ArgIndex = FA->getFormatIdx();
5023  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5024  if (MD->isInstance())
5025  --ArgIndex;
5026  const Expr *Arg = CE->getArg(ArgIndex - 1);
5027 
5028  return checkFormatStringExpr(S, Arg, Args,
5029  HasVAListArg, format_idx, firstDataArg,
5030  Type, CallType, InFunctionCall,
5031  CheckedVarArgs, UncoveredArg, Offset);
5032  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5033  unsigned BuiltinID = FD->getBuiltinID();
5034  if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5035  BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5036  const Expr *Arg = CE->getArg(0);
5037  return checkFormatStringExpr(S, Arg, Args,
5038  HasVAListArg, format_idx,
5039  firstDataArg, Type, CallType,
5040  InFunctionCall, CheckedVarArgs,
5041  UncoveredArg, Offset);
5042  }
5043  }
5044  }
5045 
5046  return SLCT_NotALiteral;
5047  }
5048  case Stmt::ObjCMessageExprClass: {
5049  const auto *ME = cast<ObjCMessageExpr>(E);
5050  if (const auto *ND = ME->getMethodDecl()) {
5051  if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5052  unsigned ArgIndex = FA->getFormatIdx();
5053  const Expr *Arg = ME->getArg(ArgIndex - 1);
5054  return checkFormatStringExpr(
5055  S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5056  CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5057  }
5058  }
5059 
5060  return SLCT_NotALiteral;
5061  }
5062  case Stmt::ObjCStringLiteralClass:
5063  case Stmt::StringLiteralClass: {
5064  const StringLiteral *StrE = nullptr;
5065 
5066  if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5067  StrE = ObjCFExpr->getString();
5068  else
5069  StrE = cast<StringLiteral>(E);
5070 
5071  if (StrE) {
5072  if (Offset.isNegative() || Offset > StrE->getLength()) {
5073  // TODO: It would be better to have an explicit warning for out of
5074  // bounds literals.
5075  return SLCT_NotALiteral;
5076  }
5077  FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5078  CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5079  firstDataArg, Type, InFunctionCall, CallType,
5080  CheckedVarArgs, UncoveredArg);
5081  return SLCT_CheckedLiteral;
5082  }
5083 
5084  return SLCT_NotALiteral;
5085  }
5086  case Stmt::BinaryOperatorClass: {
5087  llvm::APSInt LResult;
5088  llvm::APSInt RResult;
5089 
5090  const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5091 
5092  // A string literal + an int offset is still a string literal.
5093  if (BinOp->isAdditiveOp()) {
5094  bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5095  bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5096 
5097  if (LIsInt != RIsInt) {
5098  BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5099 
5100  if (LIsInt) {
5101  if (BinOpKind == BO_Add) {
5102  sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5103  E = BinOp->getRHS();
5104  goto tryAgain;
5105  }
5106  } else {
5107  sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5108  E = BinOp->getLHS();
5109  goto tryAgain;
5110  }
5111  }
5112  }
5113 
5114  return SLCT_NotALiteral;
5115  }
5116  case Stmt::UnaryOperatorClass: {
5117  const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5118  auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5119  if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5120  llvm::APSInt IndexResult;
5121  if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5122  sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5123  E = ASE->getBase();
5124  goto tryAgain;
5125  }
5126  }
5127 
5128  return SLCT_NotALiteral;
5129  }
5130 
5131  default:
5132  return SLCT_NotALiteral;
5133  }
5134 }
5135 
5137  return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5138  .Case("scanf", FST_Scanf)
5139  .Cases("printf", "printf0", FST_Printf)
5140  .Cases("NSString", "CFString", FST_NSString)
5141  .Case("strftime", FST_Strftime)
5142  .Case("strfmon", FST_Strfmon)
5143  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5144  .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5145  .Case("os_trace", FST_OSLog)
5146  .Case("os_log", FST_OSLog)
5147  .Default(FST_Unknown);
5148 }
5149 
5150 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5151 /// functions) for correct use of format strings.
5152 /// Returns true if a format string has been fully checked.
5153 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5155  bool IsCXXMember,
5156  VariadicCallType CallType,
5157  SourceLocation Loc, SourceRange Range,
5158  llvm::SmallBitVector &CheckedVarArgs) {
5159  FormatStringInfo FSI;
5160  if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5161  return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5162  FSI.FirstDataArg, GetFormatStringType(Format),
5163  CallType, Loc, Range, CheckedVarArgs);
5164  return false;
5165 }
5166 
5167 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5168  bool HasVAListArg, unsigned format_idx,
5169  unsigned firstDataArg, FormatStringType Type,
5170  VariadicCallType CallType,
5171  SourceLocation Loc, SourceRange Range,
5172  llvm::SmallBitVector &CheckedVarArgs) {
5173  // CHECK: printf/scanf-like function is called with no format string.
5174  if (format_idx >= Args.size()) {
5175  Diag(Loc, diag::warn_missing_format_string) << Range;
5176  return false;
5177  }
5178 
5179  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5180 
5181  // CHECK: format string is not a string literal.
5182  //
5183  // Dynamically generated format strings are difficult to
5184  // automatically vet at compile time. Requiring that format strings
5185  // are string literals: (1) permits the checking of format strings by
5186  // the compiler and thereby (2) can practically remove the source of
5187  // many format string exploits.
5188 
5189  // Format string can be either ObjC string (e.g. @"%d") or
5190  // C string (e.g. "%d")
5191  // ObjC string uses the same format specifiers as C string, so we can use
5192  // the same format string checking logic for both ObjC and C strings.
5193  UncoveredArgHandler UncoveredArg;
5195  checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5196  format_idx, firstDataArg, Type, CallType,
5197  /*IsFunctionCall*/ true, CheckedVarArgs,
5198  UncoveredArg,
5199  /*no string offset*/ llvm::APSInt(64, false) = 0);
5200 
5201  // Generate a diagnostic where an uncovered argument is detected.
5202  if (UncoveredArg.hasUncoveredArg()) {
5203  unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5204  assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5205  UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5206  }
5207 
5208  if (CT != SLCT_NotALiteral)
5209  // Literal format string found, check done!
5210  return CT == SLCT_CheckedLiteral;
5211 
5212  // Strftime is particular as it always uses a single 'time' argument,
5213  // so it is safe to pass a non-literal string.
5214  if (Type == FST_Strftime)
5215  return false;
5216 
5217  // Do not emit diag when the string param is a macro expansion and the
5218  // format is either NSString or CFString. This is a hack to prevent
5219  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5220  // which are usually used in place of NS and CF string literals.
5221  SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5222  if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5223  return false;
5224 
5225  // If there are no arguments specified, warn with -Wformat-security, otherwise
5226  // warn only with -Wformat-nonliteral.
5227  if (Args.size() == firstDataArg) {
5228  Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5229  << OrigFormatExpr->getSourceRange();
5230  switch (Type) {
5231  default:
5232  break;
5233  case FST_Kprintf:
5234  case FST_FreeBSDKPrintf:
5235  case FST_Printf:
5236  Diag(FormatLoc, diag::note_format_security_fixit)
5237  << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5238  break;
5239  case FST_NSString:
5240  Diag(FormatLoc, diag::note_format_security_fixit)
5241  << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5242  break;
5243  }
5244  } else {
5245  Diag(FormatLoc, diag::warn_format_nonliteral)
5246  << OrigFormatExpr->getSourceRange();
5247  }
5248  return false;
5249 }
5250 
5251 namespace {
5252 
5253 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5254 protected:
5255  Sema &S;
5256  const FormatStringLiteral *FExpr;
5257  const Expr *OrigFormatExpr;
5258  const Sema::FormatStringType FSType;
5259  const unsigned FirstDataArg;
5260  const unsigned NumDataArgs;
5261  const char *Beg; // Start of format string.
5262  const bool HasVAListArg;
5264  unsigned FormatIdx;
5265  llvm::SmallBitVector CoveredArgs;
5266  bool usesPositionalArgs = false;
5267  bool atFirstArg = true;
5268  bool inFunctionCall;
5269  Sema::VariadicCallType CallType;
5270  llvm::SmallBitVector &CheckedVarArgs;
5271  UncoveredArgHandler &UncoveredArg;
5272 
5273 public:
5274  CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5275  const Expr *origFormatExpr,
5276  const Sema::FormatStringType type, unsigned firstDataArg,
5277  unsigned numDataArgs, const char *beg, bool hasVAListArg,
5278  ArrayRef<const Expr *> Args, unsigned formatIdx,
5279  bool inFunctionCall, Sema::VariadicCallType callType,
5280  llvm::SmallBitVector &CheckedVarArgs,
5281  UncoveredArgHandler &UncoveredArg)
5282  : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5283  FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5284  HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5285  inFunctionCall(inFunctionCall), CallType(callType),
5286  CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5287  CoveredArgs.resize(numDataArgs);
5288  CoveredArgs.reset();
5289  }
5290 
5291  void DoneProcessing();
5292 
5293  void HandleIncompleteSpecifier(const char *startSpecifier,
5294  unsigned specifierLen) override;
5295 
5296  void HandleInvalidLengthModifier(
5299  const char *startSpecifier, unsigned specifierLen,
5300  unsigned DiagID);
5301 
5302  void HandleNonStandardLengthModifier(
5304  const char *startSpecifier, unsigned specifierLen);
5305 
5306  void HandleNonStandardConversionSpecifier(
5308  const char *startSpecifier, unsigned specifierLen);
5309 
5310  void HandlePosition(const char *startPos, unsigned posLen) override;
5311 
5312  void HandleInvalidPosition(const char *startSpecifier,
5313  unsigned specifierLen,
5315 
5316  void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5317 
5318  void HandleNullChar(const char *nullCharacter) override;
5319 
5320  template <typename Range>
5321  static void
5322  EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5323  const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5324  bool IsStringLocation, Range StringRange,
5325  ArrayRef<FixItHint> Fixit = None);
5326 
5327 protected:
5328  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5329  const char *startSpec,
5330  unsigned specifierLen,
5331  const char *csStart, unsigned csLen);
5332 
5333  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5334  const char *startSpec,
5335  unsigned specifierLen);
5336 
5337  SourceRange getFormatStringRange();
5338  CharSourceRange getSpecifierRange(const char *startSpecifier,
5339  unsigned specifierLen);
5340  SourceLocation getLocationOfByte(const char *x);
5341 
5342  const Expr *getDataArg(unsigned i) const;
5343 
5344  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5346  const char *startSpecifier, unsigned specifierLen,
5347  unsigned argIndex);
5348 
5349  template <typename Range>
5350  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5351  bool IsStringLocation, Range StringRange,
5352  ArrayRef<FixItHint> Fixit = None);
5353 };
5354 
5355 } // namespace
5356 
5357 SourceRange CheckFormatHandler::getFormatStringRange() {
5358  return OrigFormatExpr->getSourceRange();
5359 }
5360 
5361 CharSourceRange CheckFormatHandler::
5362 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5363  SourceLocation Start = getLocationOfByte(startSpecifier);
5364  SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5365 
5366  // Advance the end SourceLocation by one due to half-open ranges.
5367  End = End.getLocWithOffset(1);
5368 
5369  return CharSourceRange::getCharRange(Start, End);
5370 }
5371 
5372 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5373  return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5374  S.getLangOpts(), S.Context.getTargetInfo());
5375 }
5376 
5377 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5378  unsigned specifierLen){
5379  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5380  getLocationOfByte(startSpecifier),
5381  /*IsStringLocation*/true,
5382  getSpecifierRange(startSpecifier, specifierLen));
5383 }
5384 
5385 void CheckFormatHandler::HandleInvalidLengthModifier(
5388  const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5389  using namespace analyze_format_string;
5390 
5391  const LengthModifier &LM = FS.getLengthModifier();
5392  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5393 
5394  // See if we know how to fix this length modifier.
5396  if (FixedLM) {
5397  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5398  getLocationOfByte(LM.getStart()),
5399  /*IsStringLocation*/true,
5400  getSpecifierRange(startSpecifier, specifierLen));
5401 
5402  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5403  << FixedLM->toString()
5404  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5405 
5406  } else {
5407  FixItHint Hint;
5408  if (DiagID == diag::warn_format_nonsensical_length)
5409  Hint = FixItHint::CreateRemoval(LMRange);
5410 
5411  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5412  getLocationOfByte(LM.getStart()),
5413  /*IsStringLocation*/true,
5414  getSpecifierRange(startSpecifier, specifierLen),
5415  Hint);
5416  }
5417 }
5418 
5419 void CheckFormatHandler::HandleNonStandardLengthModifier(
5421  const char *startSpecifier, unsigned specifierLen) {
5422  using namespace analyze_format_string;
5423 
5424  const LengthModifier &LM = FS.getLengthModifier();
5425  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5426 
5427  // See if we know how to fix this length modifier.
5429  if (FixedLM) {
5430  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5431  << LM.toString() << 0,
5432  getLocationOfByte(LM.getStart()),
5433  /*IsStringLocation*/true,
5434  getSpecifierRange(startSpecifier, specifierLen));
5435 
5436  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5437  << FixedLM->toString()
5438  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5439 
5440  } else {
5441  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5442  << LM.toString() << 0,
5443  getLocationOfByte(LM.getStart()),
5444  /*IsStringLocation*/true,
5445  getSpecifierRange(startSpecifier, specifierLen));
5446  }
5447 }
5448 
5449 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5451  const char *startSpecifier, unsigned specifierLen) {
5452  using namespace analyze_format_string;
5453 
5454  // See if we know how to fix this conversion specifier.
5456  if (FixedCS) {
5457  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5458  << CS.toString() << /*conversion specifier*/1,
5459  getLocationOfByte(CS.getStart()),
5460  /*IsStringLocation*/true,
5461  getSpecifierRange(startSpecifier, specifierLen));
5462 
5463  CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5464  S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5465  << FixedCS->toString()
5466  << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5467  } else {
5468  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5469  << CS.toString() << /*conversion specifier*/1,
5470  getLocationOfByte(CS.getStart()),
5471  /*IsStringLocation*/true,
5472  getSpecifierRange(startSpecifier, specifierLen));
5473  }
5474 }
5475 
5476 void CheckFormatHandler::HandlePosition(const char *startPos,
5477  unsigned posLen) {
5478  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5479  getLocationOfByte(startPos),
5480  /*IsStringLocation*/true,
5481  getSpecifierRange(startPos, posLen));
5482 }
5483 
5484 void
5485 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5487  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5488  << (unsigned) p,
5489  getLocationOfByte(startPos), /*IsStringLocation*/true,
5490  getSpecifierRange(startPos, posLen));
5491 }
5492 
5493 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5494  unsigned posLen) {
5495  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5496  getLocationOfByte(startPos),
5497  /*IsStringLocation*/true,
5498  getSpecifierRange(startPos, posLen));
5499 }
5500 
5501 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5502  if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5503  // The presence of a null character is likely an error.
5504  EmitFormatDiagnostic(
5505  S.PDiag(diag::warn_printf_format_string_contains_null_char),
5506  getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5507  getFormatStringRange());
5508  }
5509 }
5510 
5511 // Note that this may return NULL if there was an error parsing or building
5512 // one of the argument expressions.
5513 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5514  return Args[FirstDataArg + i];
5515 }
5516 
5517 void CheckFormatHandler::DoneProcessing() {
5518  // Does the number of data arguments exceed the number of
5519  // format conversions in the format string?
5520  if (!HasVAListArg) {
5521  // Find any arguments that weren't covered.
5522  CoveredArgs.flip();
5523  signed notCoveredArg = CoveredArgs.find_first();
5524  if (notCoveredArg >= 0) {
5525  assert((unsigned)notCoveredArg < NumDataArgs);
5526  UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5527  } else {
5528  UncoveredArg.setAllCovered();
5529  }
5530  }
5531 }
5532 
5533 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5534  const Expr *ArgExpr) {
5535  assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5536  "Invalid state");
5537 
5538  if (!ArgExpr)
5539  return;
5540 
5541  SourceLocation Loc = ArgExpr->getLocStart();
5542 
5543  if (S.getSourceManager().isInSystemMacro(Loc))
5544  return;
5545 
5546  PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5547  for (auto E : DiagnosticExprs)
5548  PDiag << E->getSourceRange();
5549 
5550  CheckFormatHandler::EmitFormatDiagnostic(
5551  S, IsFunctionCall, DiagnosticExprs[0],
5552  PDiag, Loc, /*IsStringLocation*/false,
5553  DiagnosticExprs[0]->getSourceRange());
5554 }
5555 
5556 bool
5557 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5558  SourceLocation Loc,
5559  const char *startSpec,
5560  unsigned specifierLen,
5561  const char *csStart,
5562  unsigned csLen) {
5563  bool keepGoing = true;
5564  if (argIndex < NumDataArgs) {
5565  // Consider the argument coverered, even though the specifier doesn't
5566  // make sense.
5567  CoveredArgs.set(argIndex);
5568  }
5569  else {
5570  // If argIndex exceeds the number of data arguments we
5571  // don't issue a warning because that is just a cascade of warnings (and
5572  // they may have intended '%%' anyway). We don't want to continue processing
5573  // the format string after this point, however, as we will like just get
5574  // gibberish when trying to match arguments.
5575  keepGoing = false;
5576  }
5577 
5578  StringRef Specifier(csStart, csLen);
5579 
5580  // If the specifier in non-printable, it could be the first byte of a UTF-8
5581  // sequence. In that case, print the UTF-8 code point. If not, print the byte
5582  // hex value.
5583  std::string CodePointStr;
5584  if (!llvm::sys::locale::isPrint(*csStart)) {
5585  llvm::UTF32 CodePoint;
5586  const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5587  const llvm::UTF8 *E =
5588  reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5589  llvm::ConversionResult Result =
5590  llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5591 
5592  if (Result != llvm::conversionOK) {
5593  unsigned char FirstChar = *csStart;
5594  CodePoint = (llvm::UTF32)FirstChar;
5595  }
5596 
5597  llvm::raw_string_ostream OS(CodePointStr);
5598  if (CodePoint < 256)
5599  OS << "\\x" << llvm::format("%02x", CodePoint);
5600  else if (CodePoint <= 0xFFFF)
5601  OS << "\\u" << llvm::format("%04x", CodePoint);
5602  else
5603  OS << "\\U" << llvm::format("%08x", CodePoint);
5604  OS.flush();
5605  Specifier = CodePointStr;
5606  }
5607 
5608  EmitFormatDiagnostic(
5609  S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5610  /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5611 
5612  return keepGoing;
5613 }
5614 
5615 void
5616 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5617  const char *startSpec,
5618  unsigned specifierLen) {
5619  EmitFormatDiagnostic(
5620  S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5621  Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5622 }
5623 
5624 bool
5625 CheckFormatHandler::CheckNumArgs(
5628  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5629 
5630  if (argIndex >= NumDataArgs) {
5632  ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5633  << (argIndex+1) << NumDataArgs)
5634  : S.PDiag(diag::warn_printf_insufficient_data_args);
5635  EmitFormatDiagnostic(
5636  PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5637  getSpecifierRange(startSpecifier, specifierLen));
5638 
5639  // Since more arguments than conversion tokens are given, by extension
5640  // all arguments are covered, so mark this as so.
5641  UncoveredArg.setAllCovered();
5642  return false;
5643  }
5644  return true;
5645 }
5646 
5647 template<typename Range>
5648 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5649  SourceLocation Loc,
5650  bool IsStringLocation,
5651  Range StringRange,
5653  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5654  Loc, IsStringLocation, StringRange, FixIt);
5655 }
5656 
5657 /// \brief If the format string is not within the funcion call, emit a note
5658 /// so that the function call and string are in diagnostic messages.
5659 ///
5660 /// \param InFunctionCall if true, the format string is within the function
5661 /// call and only one diagnostic message will be produced. Otherwise, an
5662 /// extra note will be emitted pointing to location of the format string.
5663 ///
5664 /// \param ArgumentExpr the expression that is passed as the format string
5665 /// argument in the function call. Used for getting locations when two
5666 /// diagnostics are emitted.
5667 ///
5668 /// \param PDiag the callee should already have provided any strings for the
5669 /// diagnostic message. This function only adds locations and fixits
5670 /// to diagnostics.
5671 ///
5672 /// \param Loc primary location for diagnostic. If two diagnostics are
5673 /// required, one will be at Loc and a new SourceLocation will be created for
5674 /// the other one.
5675 ///
5676 /// \param IsStringLocation if true, Loc points to the format string should be
5677 /// used for the note. Otherwise, Loc points to the argument list and will
5678 /// be used with PDiag.
5679 ///
5680 /// \param StringRange some or all of the string to highlight. This is
5681 /// templated so it can accept either a CharSourceRange or a SourceRange.
5682 ///
5683 /// \param FixIt optional fix it hint for the format string.
5684 template <typename Range>
5685 void CheckFormatHandler::EmitFormatDiagnostic(
5686  Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5687  const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5688  Range StringRange, ArrayRef<FixItHint> FixIt) {
5689  if (InFunctionCall) {
5690  const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5691  D << StringRange;
5692  D << FixIt;
5693  } else {
5694  S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5695  << ArgumentExpr->getSourceRange();
5696 
5697  const Sema::SemaDiagnosticBuilder &Note =
5698  S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5699  diag::note_format_string_defined);
5700 
5701  Note << StringRange;
5702  Note << FixIt;
5703  }
5704 }
5705 
5706 //===--- CHECK: Printf format string checking ------------------------------===//
5707 
5708 namespace {
5709 
5710 class CheckPrintfHandler : public CheckFormatHandler {
5711 public:
5712  CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5713  const Expr *origFormatExpr,
5714  const Sema::FormatStringType type, unsigned firstDataArg,
5715  unsigned numDataArgs, bool isObjC, const char *beg,
5716  bool hasVAListArg, ArrayRef<const Expr *> Args,
5717  unsigned formatIdx, bool inFunctionCall,
5718  Sema::VariadicCallType CallType,
5719  llvm::SmallBitVector &CheckedVarArgs,
5720  UncoveredArgHandler &UncoveredArg)
5721  : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5722  numDataArgs, beg, hasVAListArg, Args, formatIdx,
5723  inFunctionCall, CallType, CheckedVarArgs,
5724  UncoveredArg) {}
5725 
5726  bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5727 
5728  /// Returns true if '%@' specifiers are allowed in the format string.
5729  bool allowsObjCArg() const {
5730  return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5731  FSType == Sema::FST_OSTrace;
5732  }
5733 
5734  bool HandleInvalidPrintfConversionSpecifier(
5736  const char *startSpecifier,
5737  unsigned specifierLen) override;
5738 
5739  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5740  const char *startSpecifier,
5741  unsigned specifierLen) override;
5742  bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5743  const char *StartSpecifier,
5744  unsigned SpecifierLen,
5745  const Expr *E);
5746 
5747  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5748  const char *startSpecifier, unsigned specifierLen);
5749  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5750  const analyze_printf::OptionalAmount &Amt,
5751  unsigned type,
5752  const char *startSpecifier, unsigned specifierLen);
5753  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5754  const analyze_printf::OptionalFlag &flag,
5755  const char *startSpecifier, unsigned specifierLen);
5756  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5757  const analyze_printf::OptionalFlag &ignoredFlag,
5758  const analyze_printf::OptionalFlag &flag,
5759  const char *startSpecifier, unsigned specifierLen);
5760  bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5761  const Expr *E);
5762 
5763  void HandleEmptyObjCModifierFlag(const char *startFlag,
5764  unsigned flagLen) override;
5765 
5766  void HandleInvalidObjCModifierFlag(const char *startFlag,
5767  unsigned flagLen) override;
5768 
5769  void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5770  const char *flagsEnd,
5771  const char *conversionPosition)
5772  override;
5773 };
5774 
5775 } // namespace
5776 
5777 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5779  const char *startSpecifier,
5780  unsigned specifierLen) {
5783 
5784  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5785  getLocationOfByte(CS.getStart()),
5786  startSpecifier, specifierLen,
5787  CS.getStart(), CS.getLength());
5788 }
5789 
5790 bool CheckPrintfHandler::HandleAmount(
5792  unsigned k, const char *startSpecifier,
5793  unsigned specifierLen) {
5794  if (Amt.hasDataArgument()) {
5795  if (!HasVAListArg) {
5796  unsigned argIndex = Amt.getArgIndex();
5797  if (argIndex >= NumDataArgs) {
5798  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5799  << k,
5800  getLocationOfByte(Amt.getStart()),
5801  /*IsStringLocation*/true,
5802  getSpecifierRange(startSpecifier, specifierLen));
5803  // Don't do any more checking. We will just emit
5804  // spurious errors.
5805  return false;
5806  }
5807 
5808  // Type check the data argument. It should be an 'int'.
5809  // Although not in conformance with C99, we also allow the argument to be
5810  // an 'unsigned int' as that is a reasonably safe case. GCC also
5811  // doesn't emit a warning for that case.
5812  CoveredArgs.set(argIndex);
5813  const Expr *Arg = getDataArg(argIndex);
5814  if (!Arg)
5815  return false;
5816 
5817  QualType T = Arg->getType();
5818 
5819  const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5820  assert(AT.isValid());
5821 
5822  if (!AT.matchesType(S.Context, T)) {
5823  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5824  << k << AT.getRepresentativeTypeName(S.Context)
5825  << T << Arg->getSourceRange(),
5826  getLocationOfByte(Amt.getStart()),
5827  /*IsStringLocation*/true,
5828  getSpecifierRange(startSpecifier, specifierLen));
5829  // Don't do any more checking. We will just emit
5830  // spurious errors.
5831  return false;
5832  }
5833  }
5834  }
5835  return true;
5836 }
5837 
5838 void CheckPrintfHandler::HandleInvalidAmount(
5840  const analyze_printf::OptionalAmount &Amt,
5841  unsigned type,
5842  const char *startSpecifier,
5843  unsigned specifierLen) {
5846 
5847  FixItHint fixit =
5849  ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5850  Amt.getConstantLength()))
5851  : FixItHint();
5852 
5853  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5854  << type << CS.toString(),
5855  getLocationOfByte(Amt.getStart()),
5856  /*IsStringLocation*/true,
5857  getSpecifierRange(startSpecifier, specifierLen),
5858  fixit);
5859 }
5860 
5861 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5862  const analyze_printf::OptionalFlag &flag,
5863  const char *startSpecifier,
5864  unsigned specifierLen) {
5865  // Warn about pointless flag with a fixit removal.
5868  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5869  << flag.toString() << CS.toString(),
5870  getLocationOfByte(flag.getPosition()),
5871  /*IsStringLocation*/true,
5872  getSpecifierRange(startSpecifier, specifierLen),
5874  getSpecifierRange(flag.getPosition(), 1)));
5875 }
5876 
5877 void CheckPrintfHandler::HandleIgnoredFlag(
5879  const analyze_printf::OptionalFlag &ignoredFlag,
5880  const analyze_printf::OptionalFlag &flag,
5881  const char *startSpecifier,
5882  unsigned specifierLen) {
5883  // Warn about ignored flag with a fixit removal.
5884  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5885  << ignoredFlag.toString() << flag.toString(),
5886  getLocationOfByte(ignoredFlag.getPosition()),
5887  /*IsStringLocation*/true,
5888  getSpecifierRange(startSpecifier, specifierLen),
5890  getSpecifierRange(ignoredFlag.getPosition(), 1)));
5891 }
5892 
5893 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5894  unsigned flagLen) {
5895  // Warn about an empty flag.
5896  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5897  getLocationOfByte(startFlag),
5898  /*IsStringLocation*/true,
5899  getSpecifierRange(startFlag, flagLen));
5900 }
5901 
5902 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5903  unsigned flagLen) {
5904  // Warn about an invalid flag.
5905  auto Range = getSpecifierRange(startFlag, flagLen);
5906  StringRef flag(startFlag, flagLen);
5907  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5908  getLocationOfByte(startFlag),
5909  /*IsStringLocation*/true,
5910  Range, FixItHint::CreateRemoval(Range));
5911 }
5912 
5913 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5914  const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5915  // Warn about using '[...]' without a '@' conversion.
5916  auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5917  auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5918  EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5919  getLocationOfByte(conversionPosition),
5920  /*IsStringLocation*/true,
5921  Range, FixItHint::CreateRemoval(Range));
5922 }
5923 
5924 // Determines if the specified is a C++ class or struct containing
5925 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5926 // "c_str()").
5927 template<typename MemberKind>
5928 static llvm::SmallPtrSet<MemberKind*, 1>
5929 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5930  const RecordType *RT = Ty->getAs<RecordType>();
5931  llvm::SmallPtrSet<MemberKind*, 1> Results;
5932 
5933  if (!RT)
5934  return Results;
5935  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5936  if (!RD || !RD->getDefinition())
5937  return Results;
5938 
5939  LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5941  R.suppressDiagnostics();
5942 
5943  // We just need to include all members of the right kind turned up by the
5944  // filter, at this point.
5945  if (S.LookupQualifiedName(R, RT->getDecl()))
5946  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5947  NamedDecl *decl = (*I)->getUnderlyingDecl();
5948  if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5949  Results.insert(FK);
5950  }
5951  return Results;
5952 }
5953 
5954 /// Check if we could call '.c_str()' on an object.
5955 ///
5956 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5957 /// allow the call, or if it would be ambiguous).
5958 bool Sema::hasCStrMethod(const Expr *E) {
5959  using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5960 
5961  MethodSet Results =
5962  CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5963  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5964  MI != ME; ++MI)
5965  if ((*MI)->getMinRequiredArguments() == 0)
5966  return true;
5967  return false;
5968 }
5969 
5970 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5971 // better diagnostic if so. AT is assumed to be valid.
5972 // Returns true when a c_str() conversion method is found.
5973 bool CheckPrintfHandler::checkForCStrMembers(
5974  const analyze_printf::ArgType &AT, const Expr *E) {
5975  using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5976 
5977  MethodSet Results =
5978  CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5979 
5980  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5981  MI != ME; ++MI) {
5982  const CXXMethodDecl *Method = *MI;
5983  if (Method->getMinRequiredArguments() == 0 &&
5984  AT.matchesType(S.Context, Method->getReturnType())) {
5985  // FIXME: Suggest parens if the expression needs them.
5986  SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5987  S.Diag(E->getLocStart(), diag::note_printf_c_str)
5988  << "c_str()"
5989  << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5990  return true;
5991  }
5992  }
5993 
5994  return false;
5995 }
5996 
5997 bool
5998 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5999  &FS,
6000  const char *startSpecifier,
6001  unsigned specifierLen) {
6002  using namespace analyze_format_string;
6003  using namespace analyze_printf;
6004 
6005  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6006 
6007  if (FS.consumesDataArgument()) {
6008  if (atFirstArg) {
6009  atFirstArg = false;
6010  usesPositionalArgs = FS.usesPositionalArg();
6011  }
6012  else if (usesPositionalArgs != FS.usesPositionalArg()) {
6013  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6014  startSpecifier, specifierLen);
6015  return false;
6016  }
6017  }
6018 
6019  // First check if the field width, precision, and conversion specifier
6020  // have matching data arguments.
6021  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6022  startSpecifier, specifierLen)) {
6023  return false;
6024  }
6025 
6026  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6027  startSpecifier, specifierLen)) {
6028  return false;
6029  }
6030 
6031  if (!CS.consumesDataArgument()) {
6032  // FIXME: Technically specifying a precision or field width here
6033  // makes no sense. Worth issuing a warning at some point.
6034  return true;
6035  }
6036 
6037  // Consume the argument.
6038  unsigned argIndex = FS.getArgIndex();
6039  if (argIndex < NumDataArgs) {
6040  // The check to see if the argIndex is valid will come later.
6041  // We set the bit here because we may exit early from this
6042  // function if we encounter some other error.
6043  CoveredArgs.set(argIndex);
6044  }
6045 
6046  // FreeBSD kernel extensions.
6047  if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6048  CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6049  // We need at least two arguments.
6050  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6051  return false;
6052 
6053  // Claim the second argument.
6054  CoveredArgs.set(argIndex + 1);
6055 
6056  // Type check the first argument (int for %b, pointer for %D)
6057  const Expr *Ex = getDataArg(argIndex);
6058  const analyze_printf::ArgType &AT =
6059  (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6060  ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6061  if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6062  EmitFormatDiagnostic(
6063  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6064  << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6065  << false << Ex->getSourceRange(),
6066  Ex->getLocStart(), /*IsStringLocation*/false,
6067  getSpecifierRange(startSpecifier, specifierLen));
6068 
6069  // Type check the second argument (char * for both %b and %D)
6070  Ex = getDataArg(argIndex + 1);
6071  const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6072  if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6073  EmitFormatDiagnostic(
6074  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6075  << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6076  << false << Ex->getSourceRange(),
6077  Ex->getLocStart(), /*IsStringLocation*/false,
6078  getSpecifierRange(startSpecifier, specifierLen));
6079 
6080  return true;
6081  }
6082 
6083  // Check for using an Objective-C specific conversion specifier
6084  // in a non-ObjC literal.
6085  if (!allowsObjCArg() && CS.isObjCArg()) {
6086  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6087  specifierLen);
6088  }
6089 
6090  // %P can only be used with os_log.
6091  if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6092  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6093  specifierLen);
6094  }
6095 
6096  // %n is not allowed with os_log.
6097  if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6098  EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6099  getLocationOfByte(CS.getStart()),
6100  /*IsStringLocation*/ false,
6101  getSpecifierRange(startSpecifier, specifierLen));
6102 
6103  return true;
6104  }
6105 
6106  // Only scalars are allowed for os_trace.
6107  if (FSType == Sema::FST_OSTrace &&
6108  (CS.getKind() == ConversionSpecifier::PArg ||
6109  CS.getKind() == ConversionSpecifier::sArg ||
6110  CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6111  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6112  specifierLen);
6113  }
6114 
6115  // Check for use of public/private annotation outside of os_log().
6116  if (FSType != Sema::FST_OSLog) {
6117  if (FS.isPublic().isSet()) {
6118  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6119  << "public",
6120  getLocationOfByte(FS.isPublic().getPosition()),
6121  /*IsStringLocation*/ false,
6122  getSpecifierRange(startSpecifier, specifierLen));
6123  }
6124  if (FS.isPrivate().isSet()) {
6125  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6126  << "private",
6127  getLocationOfByte(FS.isPrivate().getPosition()),
6128  /*IsStringLocation*/ false,
6129  getSpecifierRange(startSpecifier, specifierLen));
6130  }
6131  }
6132 
6133  // Check for invalid use of field width
6134  if (!FS.hasValidFieldWidth()) {
6135  HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6136  startSpecifier, specifierLen);
6137  }
6138 
6139  // Check for invalid use of precision
6140  if (!FS.hasValidPrecision()) {
6141  HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6142  startSpecifier, specifierLen);
6143  }
6144 
6145  // Precision is mandatory for %P specifier.
6146  if (CS.getKind() == ConversionSpecifier::PArg &&
6147  FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6148  EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6149  getLocationOfByte(startSpecifier),
6150  /*IsStringLocation*/ false,
6151  getSpecifierRange(startSpecifier, specifierLen));
6152  }
6153 
6154  // Check each flag does not conflict with any other component.
6156  HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6157  if (!FS.hasValidLeadingZeros())
6158  HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6159  if (!FS.hasValidPlusPrefix())
6160  HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6161  if (!FS.hasValidSpacePrefix())
6162  HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6163  if (!FS.hasValidAlternativeForm())
6164  HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6165  if (!FS.hasValidLeftJustified())
6166  HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6167 
6168  // Check that flags are not ignored by another flag
6169  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6170  HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6171  startSpecifier, specifierLen);
6172  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6173  HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6174  startSpecifier, specifierLen);
6175 
6176  // Check the length modifier is valid with the given conversion specifier.
6178  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6179  diag::warn_format_nonsensical_length);
6180  else if (!FS.hasStandardLengthModifier())
6181  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6183  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6184  diag::warn_format_non_standard_conversion_spec);
6185 
6187  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6188 
6189  // The remaining checks depend on the data arguments.
6190  if (HasVAListArg)
6191  return true;
6192 
6193  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6194  return false;
6195 
6196  const Expr *Arg = getDataArg(argIndex);
6197  if (!Arg)
6198  return true;
6199 
6200  return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6201 }
6202 
6203 static bool requiresParensToAddCast(const Expr *E) {
6204  // FIXME: We should have a general way to reason about operator
6205  // precedence and whether parens are actually needed here.
6206  // Take care of a few common cases where they aren't.
6207  const Expr *Inside = E->IgnoreImpCasts();
6208  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6209  Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6210 
6211  switch (Inside->getStmtClass()) {
6212  case Stmt::ArraySubscriptExprClass:
6213  case Stmt::CallExprClass:
6214  case Stmt::CharacterLiteralClass:
6215  case Stmt::CXXBoolLiteralExprClass:
6216  case Stmt::DeclRefExprClass:
6217  case Stmt::FloatingLiteralClass:
6218  case Stmt::IntegerLiteralClass:
6219  case Stmt::MemberExprClass:
6220  case Stmt::ObjCArrayLiteralClass:
6221  case Stmt::ObjCBoolLiteralExprClass:
6222  case Stmt::ObjCBoxedExprClass:
6223  case Stmt::ObjCDictionaryLiteralClass:
6224  case Stmt::ObjCEncodeExprClass:
6225  case Stmt::ObjCIvarRefExprClass:
6226  case Stmt::ObjCMessageExprClass:
6227  case Stmt::ObjCPropertyRefExprClass:
6228  case Stmt::ObjCStringLiteralClass:
6229  case Stmt::ObjCSubscriptRefExprClass:
6230  case Stmt::ParenExprClass:
6231  case Stmt::StringLiteralClass:
6232  case Stmt::UnaryOperatorClass:
6233  return false;
6234  default:
6235  return true;
6236  }
6237 }
6238 
6239 static std::pair<QualType, StringRef>
6241  QualType IntendedTy,
6242  const Expr *E) {
6243  // Use a 'while' to peel off layers of typedefs.
6244  QualType TyTy = IntendedTy;
6245  while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6246  StringRef Name = UserTy->getDecl()->getName();
6247  QualType CastTy = llvm::StringSwitch<QualType>(Name)
6248  .Case("CFIndex", Context.getNSIntegerType())
6249  .Case("NSInteger", Context.getNSIntegerType())
6250  .Case("NSUInteger", Context.getNSUIntegerType())
6251  .Case("SInt32", Context.IntTy)
6252  .Case("UInt32", Context.UnsignedIntTy)
6253  .Default(QualType());
6254 
6255  if (!CastTy.isNull())
6256  return std::make_pair(CastTy, Name);
6257 
6258  TyTy = UserTy->desugar();
6259  }
6260 
6261  // Strip parens if necessary.
6262  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6263  return shouldNotPrintDirectly(Context,
6264  PE->getSubExpr()->getType(),
6265  PE->getSubExpr());
6266 
6267  // If this is a conditional expression, then its result type is constructed
6268  // via usual arithmetic conversions and thus there might be no necessary
6269  // typedef sugar there. Recurse to operands to check for NSInteger &
6270  // Co. usage condition.
6271  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6272  QualType TrueTy, FalseTy;
6273  StringRef TrueName, FalseName;
6274 
6275  std::tie(TrueTy, TrueName) =
6276  shouldNotPrintDirectly(Context,
6277  CO->getTrueExpr()->getType(),
6278  CO->getTrueExpr());
6279  std::tie(FalseTy, FalseName) =
6280  shouldNotPrintDirectly(Context,
6281  CO->getFalseExpr()->getType(),
6282  CO->getFalseExpr());
6283 
6284  if (TrueTy == FalseTy)
6285  return std::make_pair(TrueTy, TrueName);
6286  else if (TrueTy.isNull())
6287  return std::make_pair(FalseTy, FalseName);
6288  else if (FalseTy.isNull())
6289  return std::make_pair(TrueTy, TrueName);
6290  }
6291 
6292  return std::make_pair(QualType(), StringRef());
6293 }
6294 
6295 bool
6296 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6297  const char *StartSpecifier,
6298  unsigned SpecifierLen,
6299  const Expr *E) {
6300  using namespace analyze_format_string;
6301  using namespace analyze_printf;
6302 
6303  // Now type check the data expression that matches the
6304  // format specifier.
6305  const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6306  if (!AT.isValid())
6307  return true;
6308 
6309  QualType ExprTy = E->getType();
6310  while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6311  ExprTy = TET->getUnderlyingExpr()->getType();
6312  }
6313 
6314  analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6315 
6316  if (match == analyze_printf::ArgType::Match) {
6317  return true;
6318  }
6319 
6320  // Look through argument promotions for our error message's reported type.
6321  // This includes the integral and floating promotions, but excludes array
6322  // and function pointer decay; seeing that an argument intended to be a
6323  // string has type 'char [6]' is probably more confusing than 'char *'.
6324  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6325  if (ICE->getCastKind() == CK_IntegralCast ||
6326  ICE->getCastKind() == CK_FloatingCast) {
6327  E = ICE->getSubExpr();
6328  ExprTy = E->getType();
6329 
6330  // Check if we didn't match because of an implicit cast from a 'char'
6331  // or 'short' to an 'int'. This is done because printf is a varargs
6332  // function.
6333  if (ICE->getType() == S.Context.IntTy ||
6334  ICE->getType() == S.Context.UnsignedIntTy) {
6335  // All further checking is done on the subexpression.
6336  if (AT.matchesType(S.Context, ExprTy))
6337  return true;
6338  }
6339  }
6340  } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6341  // Special case for 'a', which has type 'int' in C.
6342  // Note, however, that we do /not/ want to treat multibyte constants like
6343  // 'MooV' as characters! This form is deprecated but still exists.
6344  if (ExprTy == S.Context.IntTy)
6345  if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6346  ExprTy = S.Context.CharTy;
6347  }
6348 
6349  // Look through enums to their underlying type.
6350  bool IsEnum = false;
6351  if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6352  ExprTy = EnumTy->getDecl()->getIntegerType();
6353  IsEnum = true;
6354  }
6355 
6356  // %C in an Objective-C context prints a unichar, not a wchar_t.
6357  // If the argument is an integer of some kind, believe the %C and suggest
6358  // a cast instead of changing the conversion specifier.
6359  QualType IntendedTy = ExprTy;
6360  if (isObjCContext() &&
6361  FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6362  if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6363  !ExprTy->isCharType()) {
6364  // 'unichar' is defined as a typedef of unsigned short, but we should
6365  // prefer using the typedef if it is visible.
6366  IntendedTy = S.Context.UnsignedShortTy;
6367 
6368  // While we are here, check if the value is an IntegerLiteral that happens
6369  // to be within the valid range.
6370  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6371  const llvm::APInt &V = IL->getValue();
6372  if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6373  return true;
6374  }
6375 
6376  LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6378  if (S.LookupName(Result, S.getCurScope())) {
6379  NamedDecl *ND = Result.getFoundDecl();
6380  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6381  if (TD->getUnderlyingType() == IntendedTy)
6382  IntendedTy = S.Context.getTypedefType(TD);
6383  }
6384  }
6385  }
6386 
6387  // Special-case some of Darwin's platform-independence types by suggesting
6388  // casts to primitive types that are known to be large enough.
6389  bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6390  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6391  QualType CastTy;
6392  std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6393  if (!CastTy.isNull()) {
6394  IntendedTy = CastTy;
6395  ShouldNotPrintDirectly = true;
6396  }
6397  }
6398 
6399  // We may be able to offer a FixItHint if it is a supported type.
6400  PrintfSpecifier fixedFS = FS;
6401  bool success =
6402  fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6403 
6404  if (success) {
6405  // Get the fix string from the fixed format specifier
6406  SmallString<16> buf;
6407  llvm::raw_svector_ostream os(buf);
6408  fixedFS.toString(os);
6409 
6410  CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6411 
6412  if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6413  unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6415  diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6416  }
6417  // In this case, the specifier is wrong and should be changed to match
6418  // the argument.
6419  EmitFormatDiagnostic(S.PDiag(diag)
6420  << AT.getRepresentativeTypeName(S.Context)
6421  << IntendedTy << IsEnum << E->getSourceRange(),
6422  E->getLocStart(),
6423  /*IsStringLocation*/ false, SpecRange,
6424  FixItHint::CreateReplacement(SpecRange, os.str()));
6425  } else {
6426  // The canonical type for formatting this value is different from the
6427  // actual type of the expression. (This occurs, for example, with Darwin's
6428  // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6429  // should be printed as 'long' for 64-bit compatibility.)
6430  // Rather than emitting a normal format/argument mismatch, we want to
6431  // add a cast to the recommended type (and correct the format string
6432  // if necessary).
6433  SmallString<16> CastBuf;
6434  llvm::raw_svector_ostream CastFix(CastBuf);
6435  CastFix << "(";
6436  IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6437  CastFix << ")";
6438 
6440  if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6441  Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6442 
6443  if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6444  // If there's already a cast present, just replace it.
6445  SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6446  Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6447 
6448  } else if (!requiresParensToAddCast(E)) {
6449  // If the expression has high enough precedence,
6450  // just write the C-style cast.
6451  Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6452  CastFix.str()));
6453  } else {
6454  // Otherwise, add parens around the expression as well as the cast.
6455  CastFix << "(";
6456  Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6457  CastFix.str()));
6458 
6460  Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6461  }
6462 
6463  if (ShouldNotPrintDirectly) {
6464  // The expression has a type that should not be printed directly.
6465  // We extract the name from the typedef because we don't want to show
6466  // the underlying type in the diagnostic.
6467  StringRef Name;
6468  if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6469  Name = TypedefTy->getDecl()->getName();
6470  else
6471  Name = CastTyName;
6472  EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6473  << Name << IntendedTy << IsEnum
6474  << E->getSourceRange(),
6475  E->getLocStart(), /*IsStringLocation=*/false,
6476  SpecRange, Hints);
6477  } else {
6478  // In this case, the expression could be printed using a different
6479  // specifier, but we've decided that the specifier is probably correct
6480  // and we should cast instead. Just use the normal warning message.
6481  EmitFormatDiagnostic(
6482  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6483  << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6484  << E->getSourceRange(),
6485  E->getLocStart(), /*IsStringLocation*/false,
6486  SpecRange, Hints);
6487  }
6488  }
6489  } else {
6490  const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6491  SpecifierLen);
6492  // Since the warning for passing non-POD types to variadic functions
6493  // was deferred until now, we emit a warning for non-POD
6494  // arguments here.
6495  switch (S.isValidVarArgType(ExprTy)) {
6496  case Sema::VAK_Valid:
6497  case Sema::VAK_ValidInCXX11: {
6498  unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6500  diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6501  }
6502 
6503  EmitFormatDiagnostic(
6504  S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6505  << IsEnum << CSR << E->getSourceRange(),
6506  E->getLocStart(), /*IsStringLocation*/ false, CSR);
6507  break;
6508  }
6509  case Sema::VAK_Undefined:
6511  EmitFormatDiagnostic(
6512  S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6513  << S.getLangOpts().CPlusPlus11
6514  << ExprTy
6515  << CallType
6516  << AT.getRepresentativeTypeName(S.Context)
6517  << CSR
6518  << E->getSourceRange(),
6519  E->getLocStart(), /*IsStringLocation*/false, CSR);
6520  checkForCStrMembers(AT, E);
6521  break;
6522 
6523  case Sema::VAK_Invalid:
6524  if (ExprTy->isObjCObjectType())
6525  EmitFormatDiagnostic(
6526  S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6527  << S.getLangOpts().CPlusPlus11
6528  << ExprTy
6529  << CallType
6530  << AT.getRepresentativeTypeName(S.Context)
6531  << CSR
6532  << E->getSourceRange(),
6533  E->getLocStart(), /*IsStringLocation*/false, CSR);
6534  else
6535  // FIXME: If this is an initializer list, suggest removing the braces
6536  // or inserting a cast to the target type.
6537  S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6538  << isa<InitListExpr>(E) << ExprTy << CallType
6539  << AT.getRepresentativeTypeName(S.Context)
6540  << E->getSourceRange();
6541  break;
6542  }
6543 
6544  assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6545  "format string specifier index out of range");
6546  CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6547  }
6548 
6549  return true;
6550 }
6551 
6552 //===--- CHECK: Scanf format string checking ------------------------------===//
6553 
6554 namespace {
6555 
6556 class CheckScanfHandler : public CheckFormatHandler {
6557 public:
6558  CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6559  const Expr *origFormatExpr, Sema::FormatStringType type,
6560  unsigned firstDataArg, unsigned numDataArgs,
6561  const char *beg, bool hasVAListArg,
6562  ArrayRef<const Expr *> Args, unsigned formatIdx,
6563  bool inFunctionCall, Sema::VariadicCallType CallType,
6564  llvm::SmallBitVector &CheckedVarArgs,
6565  UncoveredArgHandler &UncoveredArg)
6566  : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6567  numDataArgs, beg, hasVAListArg, Args, formatIdx,
6568  inFunctionCall, CallType, CheckedVarArgs,
6569  UncoveredArg) {}
6570 
6571  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6572  const char *startSpecifier,
6573  unsigned specifierLen) override;
6574 
6575  bool HandleInvalidScanfConversionSpecifier(
6577  const char *startSpecifier,
6578  unsigned specifierLen) override;
6579 
6580  void HandleIncompleteScanList(const char *start, const char *end) override;
6581 };
6582 
6583 } // namespace
6584 
6585 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6586  const char *end) {
6587  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6588  getLocationOfByte(end), /*IsStringLocation*/true,
6589  getSpecifierRange(start, end - start));
6590 }
6591 
6592 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6594  const char *startSpecifier,
6595  unsigned specifierLen) {
6598 
6599  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6600  getLocationOfByte(CS.getStart()),
6601  startSpecifier, specifierLen,
6602  CS.getStart(), CS.getLength());
6603 }
6604 
6605 bool CheckScanfHandler::HandleScanfSpecifier(
6607  const char *startSpecifier,
6608  unsigned specifierLen) {
6609  using namespace analyze_scanf;
6610  using namespace analyze_format_string;
6611 
6612  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6613 
6614  // Handle case where '%' and '*' don't consume an argument. These shouldn't
6615  // be used to decide if we are using positional arguments consistently.
6616  if (FS.consumesDataArgument()) {
6617  if (atFirstArg) {
6618  atFirstArg = false;
6619  usesPositionalArgs = FS.usesPositionalArg();
6620  }
6621  else if (usesPositionalArgs != FS.usesPositionalArg()) {
6622  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6623  startSpecifier, specifierLen);
6624  return false;
6625  }
6626  }
6627 
6628  // Check if the field with is non-zero.
6629  const OptionalAmount &Amt = FS.getFieldWidth();
6630  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6631  if (Amt.getConstantAmount() == 0) {
6632  const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6633  Amt.getConstantLength());
6634  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6635  getLocationOfByte(Amt.getStart()),
6636  /*IsStringLocation*/true, R,
6638  }
6639  }
6640 
6641  if (!FS.consumesDataArgument()) {
6642  // FIXME: Technically specifying a precision or field width here
6643  // makes no sense. Worth issuing a warning at some point.
6644  return true;
6645  }
6646 
6647  // Consume the argument.
6648  unsigned argIndex = FS.getArgIndex();
6649  if (argIndex < NumDataArgs) {
6650  // The check to see if the argIndex is valid will come later.
6651  // We set the bit here because we may exit early from this
6652  // function if we encounter some other error.
6653  CoveredArgs.set(argIndex);
6654  }
6655 
6656  // Check the length modifier is valid with the given conversion specifier.
6658  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6659  diag::warn_format_nonsensical_length);
6660  else if (!FS.hasStandardLengthModifier())
6661  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6663  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6664  diag::warn_format_non_standard_conversion_spec);
6665 
6667  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6668 
6669  // The remaining checks depend on the data arguments.
6670  if (HasVAListArg)
6671  return true;
6672 
6673  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6674  return false;
6675 
6676  // Check that the argument type matches the format specifier.
6677  const Expr *Ex = getDataArg(argIndex);
6678  if (!Ex)
6679  return true;
6680 
6682 
6683  if (!AT.isValid()) {
6684  return true;
6685  }
6686 
6688  AT.matchesType(S.Context, Ex->getType());
6690  return true;
6691  }
6692 
6693  ScanfSpecifier fixedFS = FS;
6694  bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6695  S.getLangOpts(), S.Context);
6696 
6697  unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6699  diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6700  }
6701 
6702  if (success) {
6703  // Get the fix string from the fixed format specifier.
6704  SmallString<128> buf;
6705  llvm::raw_svector_ostream os(buf);
6706  fixedFS.toString(os);
6707 
6708  EmitFormatDiagnostic(
6709  S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6710  << Ex->getType() << false << Ex->getSourceRange(),
6711  Ex->getLocStart(),
6712  /*IsStringLocation*/ false,
6713  getSpecifierRange(startSpecifier, specifierLen),
6715  getSpecifierRange(startSpecifier, specifierLen), os.str()));
6716  } else {
6717  EmitFormatDiagnostic(S.PDiag(diag)
6719  << Ex->getType() << false << Ex->getSourceRange(),
6720  Ex->getLocStart(),
6721  /*IsStringLocation*/ false,
6722  getSpecifierRange(startSpecifier, specifierLen));
6723  }
6724 
6725  return true;
6726 }
6727 
6728 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6729  const Expr *OrigFormatExpr,
6730  ArrayRef<const Expr *> Args,
6731  bool HasVAListArg, unsigned format_idx,
6732  unsigned firstDataArg,
6734  bool inFunctionCall,
6735  Sema::VariadicCallType CallType,
6736  llvm::SmallBitVector &CheckedVarArgs,
6737  UncoveredArgHandler &UncoveredArg) {
6738  // CHECK: is the format string a wide literal?
6739  if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6740  CheckFormatHandler::EmitFormatDiagnostic(
6741  S, inFunctionCall, Args[format_idx],
6742  S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6743  /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6744  return;
6745  }
6746 
6747  // Str - The format string. NOTE: this is NOT null-terminated!
6748  StringRef StrRef = FExpr->getString();
6749  const char *Str = StrRef.data();
6750  // Account for cases where the string literal is truncated in a declaration.
6751  const ConstantArrayType *T =
6752  S.Context.getAsConstantArrayType(FExpr->getType());
6753  assert(T && "String literal not of constant array type!");
6754  size_t TypeSize = T->getSize().getZExtValue();
6755  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6756  const unsigned numDataArgs = Args.size() - firstDataArg;
6757 
6758  // Emit a warning if the string literal is truncated and does not contain an
6759  // embedded null character.
6760  if (TypeSize <= StrRef.size() &&
6761  StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6762  CheckFormatHandler::EmitFormatDiagnostic(
6763  S, inFunctionCall, Args[format_idx],
6764  S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6765  FExpr->getLocStart(),
6766  /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6767  return;
6768  }
6769 
6770  // CHECK: empty format string?
6771  if (StrLen == 0 && numDataArgs > 0) {
6772  CheckFormatHandler::EmitFormatDiagnostic(
6773  S, inFunctionCall, Args[format_idx],
6774  S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6775  /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6776  return;
6777  }
6778 
6779  if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6780  Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6781  Type == Sema::FST_OSTrace) {
6782  CheckPrintfHandler H(
6783  S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6784  (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6785  HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6786  CheckedVarArgs, UncoveredArg);
6787 
6788  if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6789  S.getLangOpts(),
6790  S.Context.getTargetInfo(),
6791  Type == Sema::FST_FreeBSDKPrintf))
6792  H.DoneProcessing();
6793  } else if (Type == Sema::FST_Scanf) {
6794  CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6795  numDataArgs, Str, HasVAListArg, Args, format_idx,
6796  inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6797 
6798  if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6799  S.getLangOpts(),
6800  S.Context.getTargetInfo()))
6801  H.DoneProcessing();
6802  } // TODO: handle other formats
6803 }
6804 
6806  // Str - The format string. NOTE: this is NOT null-terminated!
6807  StringRef StrRef = FExpr->getString();
6808  const char *Str = StrRef.data();
6809  // Account for cases where the string literal is truncated in a declaration.
6810  const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6811  assert(T && "String literal not of constant array type!");
6812  size_t TypeSize = T->getSize().getZExtValue();
6813  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6814  return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6815  getLangOpts(),
6816  Context.getTargetInfo());
6817 }
6818 
6819 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6820 
6821 // Returns the related absolute value function that is larger, of 0 if one
6822 // does not exist.
6823 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6824  switch (AbsFunction) {
6825  default:
6826  return 0;
6827 
6828  case Builtin::BI__builtin_abs:
6829  return Builtin::BI__builtin_labs;
6830  case Builtin::BI__builtin_labs:
6831  return Builtin::BI__builtin_llabs;
6832  case Builtin::BI__builtin_llabs:
6833  return 0;
6834 
6835  case Builtin::BI__builtin_fabsf:
6836  return Builtin::BI__builtin_fabs;
6837  case Builtin::BI__builtin_fabs:
6838  return Builtin::BI__builtin_fabsl;
6839  case Builtin::BI__builtin_fabsl:
6840  return 0;
6841 
6842  case Builtin::BI__builtin_cabsf:
6843  return Builtin::BI__builtin_cabs;
6844  case Builtin::BI__builtin_cabs:
6845  return Builtin::BI__builtin_cabsl;
6846  case Builtin::BI__builtin_cabsl:
6847  return 0;
6848 
6849  case Builtin::BIabs:
6850  return Builtin::BIlabs;
6851  case Builtin::BIlabs:
6852  return Builtin::BIllabs;
6853  case Builtin::BIllabs:
6854  return 0;
6855 
6856  case Builtin::BIfabsf:
6857  return Builtin::BIfabs;
6858  case Builtin::BIfabs:
6859  return Builtin::BIfabsl;
6860  case Builtin::BIfabsl:
6861  return 0;
6862 
6863  case Builtin::BIcabsf:
6864  return Builtin::BIcabs;
6865  case Builtin::BIcabs:
6866  return Builtin::BIcabsl;
6867  case Builtin::BIcabsl:
6868  return 0;
6869  }
6870 }
6871 
6872 // Returns the argument type of the absolute value function.
6874  unsigned AbsType) {
6875  if (AbsType == 0)
6876  return QualType();
6877 
6879  QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6880  if (Error != ASTContext::GE_None)
6881  return QualType();
6882 
6883  const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6884  if (!FT)
6885  return QualType();
6886 
6887  if (FT->getNumParams() != 1)
6888  return QualType();
6889 
6890  return FT->getParamType(0);
6891 }
6892 
6893 // Returns the best absolute value function, or zero, based on type and
6894 // current absolute value function.
6895 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6896  unsigned AbsFunctionKind) {
6897  unsigned BestKind = 0;
6898  uint64_t ArgSize = Context.getTypeSize(ArgType);
6899  for (unsigned Kind = AbsFunctionKind; Kind != 0;
6901  QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6902  if (Context.getTypeSize(ParamType) >= ArgSize) {
6903  if (BestKind == 0)
6904  BestKind = Kind;
6905  else if (Context.hasSameType(ParamType, ArgType)) {
6906  BestKind = Kind;
6907  break;
6908  }
6909  }
6910  }
6911  return BestKind;
6912 }
6913 
6918 };
6919 
6921  if (T->isIntegralOrEnumerationType())
6922  return AVK_Integer;
6923  if (T->isRealFloatingType())
6924  return AVK_Floating;
6925  if (T->isAnyComplexType())
6926  return AVK_Complex;
6927 
6928  llvm_unreachable("Type not integer, floating, or complex");
6929 }
6930 
6931 // Changes the absolute value function to a different type. Preserves whether
6932 // the function is a builtin.
6933 static unsigned changeAbsFunction(unsigned AbsKind,
6934  AbsoluteValueKind ValueKind) {
6935  switch (ValueKind) {
6936  case AVK_Integer:
6937  switch (AbsKind) {
6938  default:
6939  return 0;
6940  case Builtin::BI__builtin_fabsf:
6941  case Builtin::BI__builtin_fabs:
6942  case Builtin::BI__builtin_fabsl:
6943  case Builtin::BI__builtin_cabsf:
6944  case Builtin::BI__builtin_cabs:
6945  case Builtin::BI__builtin_cabsl:
6946  return Builtin::BI__builtin_abs;
6947  case Builtin::BIfabsf:
6948  case Builtin::BIfabs:
6949  case Builtin::BIfabsl:
6950  case Builtin::BIcabsf:
6951  case Builtin::BIcabs:
6952  case Builtin::BIcabsl:
6953  return Builtin::BIabs;
6954  }
6955  case AVK_Floating:
6956  switch (AbsKind) {
6957  default:
6958  return 0;
6959  case Builtin::BI__builtin_abs:
6960  case Builtin::BI__builtin_labs:
6961  case Builtin::BI__builtin_llabs:
6962  case Builtin::BI__builtin_cabsf:
6963  case Builtin::BI__builtin_cabs:
6964  case Builtin::BI__builtin_cabsl:
6965  return Builtin::BI__builtin_fabsf;
6966  case Builtin::BIabs:
6967  case Builtin::BIlabs:
6968  case Builtin::BIllabs:
6969  case Builtin::BIcabsf:
6970  case Builtin::BIcabs:
6971  case Builtin::BIcabsl:
6972  return Builtin::BIfabsf;
6973  }
6974  case AVK_Complex:
6975  switch (AbsKind) {
6976  default:
6977  return 0;
6978  case Builtin::BI__builtin_abs:
6979  case Builtin::BI__builtin_labs:
6980  case Builtin::BI__builtin_llabs:
6981  case Builtin::BI__builtin_fabsf:
6982  case Builtin::BI__builtin_fabs:
6983  case Builtin::BI__builtin_fabsl:
6984  return Builtin::BI__builtin_cabsf;
6985  case Builtin::BIabs:
6986  case Builtin::BIlabs:
6987  case Builtin::BIllabs:
6988  case Builtin::BIfabsf:
6989  case Builtin::BIfabs:
6990  case Builtin::BIfabsl:
6991  return Builtin::BIcabsf;
6992  }
6993  }
6994  llvm_unreachable("Unable to convert function");
6995 }
6996 
6997 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6998  const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6999  if (!FnInfo)
7000  return 0;
7001 
7002  switch (FDecl->getBuiltinID()) {
7003  default:
7004  return 0;
7005  case Builtin::BI__builtin_abs:
7006  case Builtin::BI__builtin_fabs:
7007  case Builtin::BI__builtin_fabsf:
7008  case Builtin::BI__builtin_fabsl:
7009  case Builtin::BI__builtin_labs:
7010  case Builtin::BI__builtin_llabs:
7011  case Builtin::BI__builtin_cabs:
7012  case Builtin::BI__builtin_cabsf:
7013  case Builtin::BI__builtin_cabsl:
7014  case Builtin::BIabs:
7015  case Builtin::BIlabs:
7016  case Builtin::BIllabs:
7017  case Builtin::BIfabs:
7018  case Builtin::BIfabsf:
7019  case Builtin::BIfabsl:
7020  case Builtin::BIcabs:
7021  case Builtin::BIcabsf:
7022  case Builtin::BIcabsl:
7023  return FDecl->getBuiltinID();
7024  }
7025  llvm_unreachable("Unknown Builtin type");
7026 }
7027 
7028 // If the replacement is valid, emit a note with replacement function.
7029 // Additionally, suggest including the proper header if not already included.
7030 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7031  unsigned AbsKind, QualType ArgType) {
7032  bool EmitHeaderHint = true;
7033  const char *HeaderName = nullptr;
7034  const char *FunctionName = nullptr;
7035  if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7036  FunctionName = "std::abs";
7037  if (ArgType->isIntegralOrEnumerationType()) {
7038  HeaderName = "cstdlib";
7039  } else if (ArgType->isRealFloatingType()) {
7040  HeaderName = "cmath";
7041  } else {
7042  llvm_unreachable("Invalid Type");
7043  }
7044 
7045  // Lookup all std::abs
7046  if (NamespaceDecl *Std = S.getStdNamespace()) {
7047  LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7048  R.suppressDiagnostics();
7049  S.LookupQualifiedName(R, Std);
7050 
7051  for (const auto *I : R) {
7052  const FunctionDecl *FDecl = nullptr;
7053  if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7054  FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7055  } else {
7056  FDecl = dyn_cast<FunctionDecl>(I);
7057  }
7058  if (!FDecl)
7059  continue;
7060 
7061  // Found std::abs(), check that they are the right ones.
7062  if (FDecl->getNumParams() != 1)
7063  continue;
7064 
7065  // Check that the parameter type can handle the argument.
7066  QualType ParamType = FDecl->getParamDecl(0)->getType();
7067  if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7068  S.Context.getTypeSize(ArgType) <=
7069  S.Context.getTypeSize(ParamType)) {
7070  // Found a function, don't need the header hint.
7071  EmitHeaderHint = false;
7072  break;
7073  }
7074  }
7075  }
7076  } else {
7077  FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7078  HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7079 
7080  if (HeaderName) {
7081  DeclarationName DN(&S.Context.Idents.get(FunctionName));
7082  LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7083  R.suppressDiagnostics();
7084  S.LookupName(R, S.getCurScope());
7085 
7086  if (R.isSingleResult()) {
7087  FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7088  if (FD && FD->getBuiltinID() == AbsKind) {
7089  EmitHeaderHint = false;
7090  } else {
7091  return;
7092  }
7093  } else if (!R.empty()) {
7094  return;
7095  }
7096  }
7097  }
7098 
7099  S.Diag(Loc, diag::note_replace_abs_function)
7100  << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7101 
7102  if (!HeaderName)
7103  return;
7104 
7105  if (!EmitHeaderHint)
7106  return;
7107 
7108  S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7109  << FunctionName;
7110 }
7111 
7112 template <std::size_t StrLen>
7113 static bool IsStdFunction(const FunctionDecl *FDecl,
7114  const char (&Str)[StrLen]) {
7115  if (!FDecl)
7116  return false;
7117  if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7118  return false;
7119  if (!FDecl->isInStdNamespace())
7120  return false;
7121 
7122  return true;
7123 }
7124 
7125 // Warn when using the wrong abs() function.
7126 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7127  const FunctionDecl *FDecl) {
7128  if (Call->getNumArgs() != 1)
7129  return;
7130 
7131  unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7132  bool IsStdAbs = IsStdFunction(FDecl, "abs");
7133  if (AbsKind == 0 && !IsStdAbs)
7134  return;
7135 
7136  QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7137  QualType ParamType = Call->getArg(0)->getType();
7138 
7139  // Unsigned types cannot be negative. Suggest removing the absolute value
7140  // function call.
7141  if (ArgType->isUnsignedIntegerType()) {
7142  const char *FunctionName =
7143  IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7144  Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7145  Diag(Call->getExprLoc(), diag::note_remove_abs)
7146  << FunctionName
7148  return;
7149  }
7150 
7151  // Taking the absolute value of a pointer is very suspicious, they probably
7152  // wanted to index into an array, dereference a pointer, call a function, etc.
7153  if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7154  unsigned DiagType = 0;
7155  if (ArgType->isFunctionType())
7156  DiagType = 1;
7157  else if (ArgType->isArrayType())
7158  DiagType = 2;
7159 
7160  Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7161  return;
7162  }
7163 
7164  // std::abs has overloads which prevent most of the absolute value problems
7165  // from occurring.
7166  if (IsStdAbs)
7167  return;
7168 
7169  AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7170  AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7171 
7172  // The argument and parameter are the same kind. Check if they are the right
7173  // size.
7174  if (ArgValueKind == ParamValueKind) {
7175  if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7176  return;
7177 
7178  unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7179  Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7180  << FDecl << ArgType << ParamType;
7181 
7182  if (NewAbsKind == 0)
7183  return;
7184 
7185  emitReplacement(*this, Call->getExprLoc(),
7186  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7187  return;
7188  }
7189 
7190  // ArgValueKind != ParamValueKind
7191  // The wrong type of absolute value function was used. Attempt to find the
7192  // proper one.
7193  unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7194  NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7195  if (NewAbsKind == 0)
7196  return;
7197 
7198  Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7199  << FDecl << ParamValueKind << ArgValueKind;
7200 
7201  emitReplacement(*this, Call->getExprLoc(),
7202  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7203 }
7204 
7205 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7206 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7207  const FunctionDecl *FDecl) {
7208  if (!Call || !FDecl) return;
7209 
7210  // Ignore template specializations and macros.
7211  if (inTemplateInstantiation()) return;
7212  if (Call->getExprLoc().isMacroID()) return;
7213 
7214  // Only care about the one template argument, two function parameter std::max
7215  if (Call->getNumArgs() != 2) return;
7216  if (!IsStdFunction(FDecl, "max")) return;
7217  const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7218  if (!ArgList) return;
7219  if (ArgList->size() != 1) return;
7220 
7221  // Check that template type argument is unsigned integer.
7222  const auto& TA = ArgList->get(0);
7223  if (TA.getKind() != TemplateArgument::Type) return;
7224  QualType ArgType = TA.getAsType();
7225  if (!ArgType->isUnsignedIntegerType()) return;
7226 
7227  // See if either argument is a literal zero.
7228  auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7229  const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7230  if (!MTE) return false;
7231  const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7232  if (!Num) return false;
7233  if (Num->getValue() != 0) return false;
7234  return true;
7235  };
7236 
7237  const Expr *FirstArg = Call->getArg(0);
7238  const Expr *SecondArg = Call->getArg(1);
7239  const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7240  const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7241 
7242  // Only warn when exactly one argument is zero.
7243  if (IsFirstArgZero == IsSecondArgZero) return;
7244 
7245  SourceRange FirstRange = FirstArg->getSourceRange();
7246  SourceRange SecondRange = SecondArg->getSourceRange();
7247 
7248  SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7249 
7250  Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7251  << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7252 
7253  // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7254  SourceRange RemovalRange;
7255  if (IsFirstArgZero) {
7256  RemovalRange = SourceRange(FirstRange.getBegin(),
7257  SecondRange.getBegin().getLocWithOffset(-1));
7258  } else {
7259  RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7260  SecondRange.getEnd());
7261  }
7262 
7263  Diag(Call->getExprLoc(), diag::note_remove_max_call)
7265  << FixItHint::CreateRemoval(RemovalRange);
7266 }
7267 
7268 //===--- CHECK: Standard memory functions ---------------------------------===//
7269 
7270 /// \brief Takes the expression passed to the size_t parameter of functions
7271 /// such as memcmp, strncat, etc and warns if it's a comparison.
7272 ///
7273 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7274 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7275  IdentifierInfo *FnName,
7276  SourceLocation FnLoc,
7277  SourceLocation RParenLoc) {
7278  const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7279  if (!Size)
7280  return false;
7281 
7282  // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7283  if (!Size->isComparisonOp() && !Size->isLogicalOp())
7284  return false;
7285 
7286  SourceRange SizeRange = Size->getSourceRange();
7287  S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7288  << SizeRange << FnName;
7289  S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7290  << FnName << FixItHint::CreateInsertion(
7291  S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7292  << FixItHint::CreateRemoval(RParenLoc);
7293  S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7294  << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7296  ")");
7297 
7298  return true;
7299 }
7300 
7301 /// \brief Determine whether the given type is or contains a dynamic class type
7302 /// (e.g., whether it has a vtable).
7304  bool &IsContained) {
7305  // Look through array types while ignoring qualifiers.
7306  const Type *Ty = T->getBaseElementTypeUnsafe();
7307  IsContained = false;
7308 
7309  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7310  RD = RD ? RD->getDefinition() : nullptr;
7311  if (!RD || RD->isInvalidDecl())
7312  return nullptr;
7313 
7314  if (RD->isDynamicClass())
7315  return RD;
7316 
7317  // Check all the fields. If any bases were dynamic, the class is dynamic.
7318  // It's impossible for a class to transitively contain itself by value, so
7319  // infinite recursion is impossible.
7320  for (auto *FD : RD->fields()) {
7321  bool SubContained;
7322  if (const CXXRecordDecl *ContainedRD =
7323  getContainedDynamicClass(FD->getType(), SubContained)) {
7324  IsContained = true;
7325  return ContainedRD;
7326  }
7327  }
7328 
7329  return nullptr;
7330 }
7331 
7332 /// \brief If E is a sizeof expression, returns its argument expression,
7333 /// otherwise returns NULL.
7334 static const Expr *getSizeOfExprArg(const Expr *E) {
7335  if (const UnaryExprOrTypeTraitExpr *SizeOf =
7336  dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7337  if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7338  return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7339 
7340  return nullptr;
7341 }
7342 
7343 /// \brief If E is a sizeof expression, returns its argument type.
7344 static QualType getSizeOfArgType(const Expr *E) {
7345  if (const UnaryExprOrTypeTraitExpr *SizeOf =
7346  dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7347  if (SizeOf->getKind() == UETT_SizeOf)
7348  return SizeOf->getTypeOfArgument();
7349 
7350  return QualType();
7351 }
7352 
7353 /// \brief Check for dangerous or invalid arguments to memset().
7354 ///
7355 /// This issues warnings on known problematic, dangerous or unspecified
7356 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7357 /// function calls.
7358 ///
7359 /// \param Call The call expression to diagnose.
7360 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7361  unsigned BId,
7362  IdentifierInfo *FnName) {
7363  assert(BId != 0);
7364 
7365  // It is possible to have a non-standard definition of memset. Validate
7366  // we have enough arguments, and if not, abort further checking.
7367  unsigned ExpectedNumArgs =
7368  (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7369  if (Call->getNumArgs() < ExpectedNumArgs)
7370  return;
7371 
7372  unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7373  BId == Builtin::BIstrndup ? 1 : 2);
7374  unsigned LenArg =
7375  (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7376  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7377 
7378  if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7379  Call->getLocStart(), Call->getRParenLoc()))
7380  return;
7381 
7382  // We have special checking when the length is a sizeof expression.
7383  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7384  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7385  llvm::FoldingSetNodeID SizeOfArgID;
7386 
7387  // Although widely used, 'bzero' is not a standard function. Be more strict
7388  // with the argument types before allowing diagnostics and only allow the
7389  // form bzero(ptr, sizeof(...)).
7390  QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7391  if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7392  return;
7393 
7394  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7395  const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7396  SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7397 
7398  QualType DestTy = Dest->getType();
7399  QualType PointeeTy;
7400  if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7401  PointeeTy = DestPtrTy->getPointeeType();
7402 
7403  // Never warn about void type pointers. This can be used to suppress
7404  // false positives.
7405  if (PointeeTy->isVoidType())
7406  continue;
7407 
7408  // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7409  // actually comparing the expressions for equality. Because computing the
7410  // expression IDs can be expensive, we only do this if the diagnostic is
7411  // enabled.
7412  if (SizeOfArg &&
7413  !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7414  SizeOfArg->getExprLoc())) {
7415  // We only compute IDs for expressions if the warning is enabled, and
7416  // cache the sizeof arg's ID.
7417  if (SizeOfArgID == llvm::FoldingSetNodeID())
7418  SizeOfArg->Profile(SizeOfArgID, Context, true);
7419  llvm::FoldingSetNodeID DestID;
7420  Dest->Profile(DestID, Context, true);
7421  if (DestID == SizeOfArgID) {
7422  // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7423  // over sizeof(src) as well.
7424  unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7425  StringRef ReadableName = FnName->getName();
7426 
7427  if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7428  if (UnaryOp->getOpcode() == UO_AddrOf)
7429  ActionIdx = 1; // If its an address-of operator, just remove it.
7430  if (!PointeeTy->isIncompleteType() &&
7431  (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7432  ActionIdx = 2; // If the pointee's size is sizeof(char),
7433  // suggest an explicit length.
7434 
7435  // If the function is defined as a builtin macro, do not show macro
7436  // expansion.
7437  SourceLocation SL = SizeOfArg->getExprLoc();
7438  SourceRange DSR = Dest->getSourceRange();
7439  SourceRange SSR = SizeOfArg->getSourceRange();
7440  SourceManager &SM = getSourceManager();
7441 
7442  if (SM.isMacroArgExpansion(SL)) {
7443  ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7444  SL = SM.getSpellingLoc(SL);
7445  DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7446  SM.getSpellingLoc(DSR.getEnd()));
7447  SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7448  SM.getSpellingLoc(SSR.getEnd()));
7449  }
7450 
7451  DiagRuntimeBehavior(SL, SizeOfArg,
7452  PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7453  << ReadableName
7454  << PointeeTy
7455  << DestTy
7456  << DSR
7457  << SSR);
7458  DiagRuntimeBehavior(SL, SizeOfArg,
7459  PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7460  << ActionIdx
7461  << SSR);
7462 
7463  break;
7464  }
7465  }
7466 
7467  // Also check for cases where the sizeof argument is the exact same
7468  // type as the memory argument, and where it points to a user-defined
7469  // record type.
7470  if (SizeOfArgTy != QualType()) {
7471  if (PointeeTy->isRecordType() &&
7472  Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7473  DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7474  PDiag(diag::warn_sizeof_pointer_type_memaccess)
7475  << FnName << SizeOfArgTy << ArgIdx
7476  << PointeeTy << Dest->getSourceRange()
7477  << LenExpr->getSourceRange());
7478  break;
7479  }
7480  }
7481  } else if (DestTy->isArrayType()) {
7482  PointeeTy = DestTy;
7483  }
7484 
7485  if (PointeeTy == QualType())
7486  continue;
7487 
7488  // Always complain about dynamic classes.
7489  bool IsContained;
7490  if (const CXXRecordDecl *ContainedRD =
7491  getContainedDynamicClass(PointeeTy, IsContained)) {
7492 
7493  unsigned OperationType = 0;
7494  // "overwritten" if we're warning about the destination for any call
7495  // but memcmp; otherwise a verb appropriate to the call.
7496  if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7497  if (BId == Builtin::BImemcpy)
7498  OperationType = 1;
7499  else if(BId == Builtin::BImemmove)
7500  OperationType = 2;
7501  else if (BId == Builtin::BImemcmp)
7502  OperationType = 3;
7503  }
7504 
7505  DiagRuntimeBehavior(
7506  Dest->getExprLoc(), Dest,
7507  PDiag(diag::warn_dyn_class_memaccess)
7508  << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7509  << FnName << IsContained << ContainedRD << OperationType
7510  << Call->getCallee()->getSourceRange());
7511  } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7512  BId != Builtin::BImemset)
7513  DiagRuntimeBehavior(
7514  Dest->getExprLoc(), Dest,
7515  PDiag(diag::warn_arc_object_memaccess)
7516  << ArgIdx << FnName << PointeeTy
7517  << Call->getCallee()->getSourceRange());
7518  else
7519  continue;
7520 
7521  DiagRuntimeBehavior(
7522  Dest->getExprLoc(), Dest,
7523  PDiag(diag::note_bad_memaccess_silence)
7524  << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7525  break;
7526  }
7527 }
7528 
7529 // A little helper routine: ignore addition and subtraction of integer literals.
7530 // This intentionally does not ignore all integer constant expressions because
7531 // we don't want to remove sizeof().
7532 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7533  Ex = Ex->IgnoreParenCasts();
7534 
7535  while (true) {
7536  const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7537  if (!BO || !BO->isAdditiveOp())
7538  break;
7539 
7540  const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7541  const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7542 
7543  if (isa<IntegerLiteral>(RHS))
7544  Ex = LHS;
7545  else if (isa<IntegerLiteral>(LHS))
7546  Ex = RHS;
7547  else
7548  break;
7549  }
7550 
7551  return Ex;
7552 }
7553 
7555  ASTContext &Context) {
7556  // Only handle constant-sized or VLAs, but not flexible members.
7557  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7558  // Only issue the FIXIT for arrays of size > 1.
7559  if (CAT->getSize().getSExtValue() <= 1)
7560  return false;
7561  } else if (!Ty->isVariableArrayType()) {
7562  return false;
7563  }
7564  return true;
7565 }
7566 
7567 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7568 // be the size of the source, instead of the destination.
7569 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7570  IdentifierInfo *FnName) {
7571 
7572  // Don't crash if the user has the wrong number of arguments
7573  unsigned NumArgs = Call->getNumArgs();
7574  if ((NumArgs != 3) && (NumArgs != 4))
7575  return;
7576 
7577  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7578  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7579  const Expr *CompareWithSrc = nullptr;
7580 
7581  if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7582  Call->getLocStart(), Call->getRParenLoc()))
7583  return;
7584 
7585  // Look for 'strlcpy(dst, x, sizeof(x))'
7586  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7587  CompareWithSrc = Ex;
7588  else {
7589  // Look for 'strlcpy(dst, x, strlen(x))'
7590  if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7591  if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7592  SizeCall->getNumArgs() == 1)
7593  CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7594  }
7595  }
7596 
7597  if (!CompareWithSrc)
7598  return;
7599 
7600  // Determine if the argument to sizeof/strlen is equal to the source
7601  // argument. In principle there's all kinds of things you could do
7602  // here, for instance creating an == expression and evaluating it with
7603  // EvaluateAsBooleanCondition, but this uses a more direct technique:
7604  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7605  if (!SrcArgDRE)
7606  return;
7607 
7608  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7609  if (!CompareWithSrcDRE ||
7610  SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7611  return;
7612 
7613  const Expr *OriginalSizeArg = Call->getArg(2);
7614  Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7615  << OriginalSizeArg->getSourceRange() << FnName;
7616 
7617  // Output a FIXIT hint if the destination is an array (rather than a
7618  // pointer to an array). This could be enhanced to handle some
7619  // pointers if we know the actual size, like if DstArg is 'array+2'
7620  // we could say 'sizeof(array)-2'.
7621  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7622  if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7623  return;
7624 
7625  SmallString<128> sizeString;
7626  llvm::raw_svector_ostream OS(sizeString);
7627  OS << "sizeof(";
7628  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7629  OS << ")";
7630 
7631  Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7632  << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7633  OS.str());
7634 }
7635 
7636 /// Check if two expressions refer to the same declaration.
7637 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7638  if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7639  if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7640  return D1->getDecl() == D2->getDecl();
7641  return false;
7642 }
7643 
7644 static const Expr *getStrlenExprArg(const Expr *E) {
7645  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7646  const FunctionDecl *FD = CE->getDirectCallee();
7647  if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7648  return nullptr;
7649  return CE->getArg(0)->IgnoreParenCasts();
7650  }
7651  return nullptr;
7652 }
7653 
7654 // Warn on anti-patterns as the 'size' argument to strncat.
7655 // The correct size argument should look like following:
7656 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7657 void Sema::CheckStrncatArguments(const CallExpr *CE,
7658  IdentifierInfo *FnName) {
7659  // Don't crash if the user has the wrong number of arguments.
7660  if (CE->getNumArgs() < 3)
7661  return;
7662  const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7663  const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7664  const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7665 
7666  if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7667  CE->getRParenLoc()))
7668  return;
7669 
7670  // Identify common expressions, which are wrongly used as the size argument
7671  // to strncat and may lead to buffer overflows.
7672  unsigned PatternType = 0;
7673  if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7674  // - sizeof(dst)
7675  if (referToTheSameDecl(SizeOfArg, DstArg))
7676  PatternType = 1;
7677  // - sizeof(src)
7678  else if (referToTheSameDecl(SizeOfArg, SrcArg))
7679  PatternType = 2;
7680  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7681  if (BE->getOpcode() == BO_Sub) {
7682  const Expr *L = BE->getLHS()->IgnoreParenCasts();
7683  const Expr *R = BE->getRHS()->IgnoreParenCasts();
7684  // - sizeof(dst) - strlen(dst)
7685  if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7687  PatternType = 1;
7688  // - sizeof(src) - (anything)
7689  else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7690  PatternType = 2;
7691  }
7692  }
7693 
7694  if (PatternType == 0)
7695  return;
7696 
7697  // Generate the diagnostic.
7698  SourceLocation SL = LenArg->getLocStart();
7699  SourceRange SR = LenArg->getSourceRange();
7700  SourceManager &SM = getSourceManager();
7701 
7702  // If the function is defined as a builtin macro, do not show macro expansion.
7703  if (SM.isMacroArgExpansion(SL)) {
7704  SL = SM.getSpellingLoc(SL);
7705  SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7706  SM.getSpellingLoc(SR.getEnd()));
7707  }
7708 
7709  // Check if the destination is an array (rather than a pointer to an array).
7710  QualType DstTy = DstArg->getType();
7711  bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7712  Context);
7713  if (!isKnownSizeArray) {
7714  if (PatternType == 1)
7715  Diag(SL, diag::warn_strncat_wrong_size) << SR;
7716  else
7717  Diag(SL, diag::warn_strncat_src_size) << SR;
7718  return;
7719  }
7720 
7721  if (PatternType == 1)
7722  Diag(SL, diag::warn_strncat_large_size) << SR;
7723  else
7724  Diag(SL, diag::warn_strncat_src_size) << SR;
7725 
7726  SmallString<128> sizeString;
7727  llvm::raw_svector_ostream OS(sizeString);
7728  OS << "sizeof(";
7729  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7730  OS << ") - ";
7731  OS << "strlen(";
7732  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7733  OS << ") - 1";
7734 
7735  Diag(SL, diag::note_strncat_wrong_size)
7736  << FixItHint::CreateReplacement(SR, OS.str());
7737 }
7738 
7739 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7740 
7741 static const Expr *EvalVal(const Expr *E,
7742  SmallVectorImpl<const DeclRefExpr *> &refVars,
7743  const Decl *ParentDecl);
7744 static const Expr *EvalAddr(const Expr *E,
7745  SmallVectorImpl<const DeclRefExpr *> &refVars,
7746  const Decl *ParentDecl);
7747 
7748 /// CheckReturnStackAddr - Check if a return statement returns the address
7749 /// of a stack variable.
7750 static void
7751 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7752  SourceLocation ReturnLoc) {
7753  const Expr *stackE = nullptr;
7755 
7756  // Perform checking for returned stack addresses, local blocks,
7757  // label addresses or references to temporaries.
7758  if (lhsType->isPointerType() ||
7759  (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7760  stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7761  } else if (lhsType->isReferenceType()) {
7762  stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7763  }
7764 
7765  if (!stackE)
7766  return; // Nothing suspicious was found.
7767 
7768  // Parameters are initialized in the calling scope, so taking the address
7769  // of a parameter reference doesn't need a warning.
7770  for (auto *DRE : refVars)
7771  if (isa<ParmVarDecl>(DRE->getDecl()))
7772  return;
7773 
7774  SourceLocation diagLoc;
7775  SourceRange diagRange;
7776  if (refVars.empty()) {
7777  diagLoc = stackE->getLocStart();
7778  diagRange = stackE->getSourceRange();
7779  } else {
7780  // We followed through a reference variable. 'stackE' contains the
7781  // problematic expression but we will warn at the return statement pointing
7782  // at the reference variable. We will later display the "trail" of
7783  // reference variables using notes.
7784  diagLoc = refVars[0]->getLocStart();
7785  diagRange = refVars[0]->getSourceRange();
7786  }
7787 
7788  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7789  // address of local var
7790  S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7791  << DR->getDecl()->getDeclName() << diagRange;
7792  } else if (isa<BlockExpr>(stackE)) { // local block.
7793  S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7794  } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7795  S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7796  } else { // local temporary.
7797  // If there is an LValue->RValue conversion, then the value of the
7798  // reference type is used, not the reference.
7799  if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7800  if (ICE->getCastKind() == CK_LValueToRValue) {
7801  return;
7802  }
7803  }
7804  S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7805  << lhsType->isReferenceType() << diagRange;
7806  }
7807 
7808  // Display the "trail" of reference variables that we followed until we
7809  // found the problematic expression using notes.
7810  for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7811  const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7812  // If this var binds to another reference var, show the range of the next
7813  // var, otherwise the var binds to the problematic expression, in which case
7814  // show the range of the expression.
7815  SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7816  : stackE->getSourceRange();
7817  S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7818  << VD->getDeclName() << range;
7819  }
7820 }
7821 
7822 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7823 /// check if the expression in a return statement evaluates to an address
7824 /// to a location on the stack, a local block, an address of a label, or a
7825 /// reference to local temporary. The recursion is used to traverse the
7826 /// AST of the return expression, with recursion backtracking when we
7827 /// encounter a subexpression that (1) clearly does not lead to one of the
7828 /// above problematic expressions (2) is something we cannot determine leads to
7829 /// a problematic expression based on such local checking.
7830 ///
7831 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
7832 /// the expression that they point to. Such variables are added to the
7833 /// 'refVars' vector so that we know what the reference variable "trail" was.
7834 ///
7835 /// EvalAddr processes expressions that are pointers that are used as
7836 /// references (and not L-values). EvalVal handles all other values.
7837 /// At the base case of the recursion is a check for the above problematic
7838 /// expressions.
7839 ///
7840 /// This implementation handles:
7841 ///
7842 /// * pointer-to-pointer casts
7843 /// * implicit conversions from array references to pointers
7844 /// * taking the address of fields
7845 /// * arbitrary interplay between "&" and "*" operators
7846 /// * pointer arithmetic from an address of a stack variable
7847 /// * taking the address of an array element where the array is on the stack
7848 static const Expr *EvalAddr(const Expr *E,
7849  SmallVectorImpl<const DeclRefExpr *> &refVars,
7850  const Decl *ParentDecl) {
7851  if (E->isTypeDependent())
7852  return nullptr;
7853 
7854  // We should only be called for evaluating pointer expressions.
7855  assert((E->getType()->isAnyPointerType() ||
7856  E->getType()->isBlockPointerType() ||
7857  E->getType()->isObjCQualifiedIdType()) &&
7858  "EvalAddr only works on pointers");
7859 
7860  E = E->IgnoreParens();
7861 
7862  // Our "symbolic interpreter" is just a dispatch off the currently
7863  // viewed AST node. We then recursively traverse the AST by calling
7864  // EvalAddr and EvalVal appropriately.
7865  switch (E->getStmtClass()) {
7866  case Stmt::DeclRefExprClass: {
7867  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7868 
7869  // If we leave the immediate function, the lifetime isn't about to end.
7871  return nullptr;
7872 
7873  if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7874  // If this is a reference variable, follow through to the expression that
7875  // it points to.
7876  if (V->hasLocalStorage() &&
7877  V->getType()->isReferenceType() && V->hasInit()) {
7878  // Add the reference variable to the "trail".
7879  refVars.push_back(DR);
7880  return EvalAddr(V->getInit(), refVars, ParentDecl);
7881  }
7882 
7883  return nullptr;
7884  }
7885 
7886  case Stmt::UnaryOperatorClass: {
7887  // The only unary operator that make sense to handle here
7888  // is AddrOf. All others don't make sense as pointers.
7889  const UnaryOperator *U = cast<UnaryOperator>(E);
7890 
7891  if (U->getOpcode() == UO_AddrOf)
7892  return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7893  return nullptr;
7894  }
7895 
7896  case Stmt::BinaryOperatorClass: {
7897  // Handle pointer arithmetic. All other binary operators are not valid
7898  // in this context.
7899  const BinaryOperator *B = cast<BinaryOperator>(E);
7900  BinaryOperatorKind op = B->getOpcode();
7901 
7902  if (op != BO_Add && op != BO_Sub)
7903  return nullptr;
7904 
7905  const Expr *Base = B->getLHS();
7906 
7907  // Determine which argument is the real pointer base. It could be
7908  // the RHS argument instead of the LHS.
7909  if (!Base->getType()->isPointerType())
7910  Base = B->getRHS();
7911 
7912  assert(Base->getType()->isPointerType());
7913  return EvalAddr(Base, refVars, ParentDecl);
7914  }
7915 
7916  // For conditional operators we need to see if either the LHS or RHS are
7917  // valid DeclRefExpr*s. If one of them is valid, we return it.
7918  case Stmt::ConditionalOperatorClass: {
7919  const ConditionalOperator *C = cast<ConditionalOperator>(E);
7920 
7921  // Handle the GNU extension for missing LHS.
7922  // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7923  if (const Expr *LHSExpr = C->getLHS()) {
7924  // In C++, we can have a throw-expression, which has 'void' type.
7925  if (!LHSExpr->getType()->isVoidType())
7926  if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7927  return LHS;
7928  }
7929 
7930  // In C++, we can have a throw-expression, which has 'void' type.
7931  if (C->getRHS()->getType()->isVoidType())
7932  return nullptr;
7933 
7934  return EvalAddr(C->getRHS(), refVars, ParentDecl);
7935  }
7936 
7937  case Stmt::BlockExprClass:
7938  if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7939  return E; // local block.
7940  return nullptr;
7941 
7942  case Stmt::AddrLabelExprClass:
7943  return E; // address of label.
7944 
7945  case Stmt::ExprWithCleanupsClass:
7946  return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7947  ParentDecl);
7948 
7949  // For casts, we need to handle conversions from arrays to
7950  // pointer values, and pointer-to-pointer conversions.
7951  case Stmt::ImplicitCastExprClass:
7952  case Stmt::CStyleCastExprClass:
7953  case Stmt::CXXFunctionalCastExprClass:
7954  case Stmt::ObjCBridgedCastExprClass:
7955  case Stmt::CXXStaticCastExprClass:
7956  case Stmt::CXXDynamicCastExprClass:
7957  case Stmt::CXXConstCastExprClass:
7958  case Stmt::CXXReinterpretCastExprClass: {
7959  const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7960  switch (cast<CastExpr>(E)->getCastKind()) {
7961  case CK_LValueToRValue:
7962  case CK_NoOp:
7963  case CK_BaseToDerived:
7964  case CK_DerivedToBase:
7965  case CK_UncheckedDerivedToBase:
7966  case CK_Dynamic:
7967  case CK_CPointerToObjCPointerCast:
7968  case CK_BlockPointerToObjCPointerCast:
7969  case CK_AnyPointerToBlockPointerCast:
7970  return EvalAddr(SubExpr, refVars, ParentDecl);
7971 
7972  case CK_ArrayToPointerDecay:
7973  return EvalVal(SubExpr, refVars, ParentDecl);
7974 
7975  case CK_BitCast:
7976  if (SubExpr->getType()->isAnyPointerType() ||
7977  SubExpr->getType()->isBlockPointerType() ||
7978  SubExpr->getType()->isObjCQualifiedIdType())
7979  return EvalAddr(SubExpr, refVars, ParentDecl);
7980  else
7981  return nullptr;
7982 
7983  default:
7984  return nullptr;
7985  }
7986  }
7987 
7988  case Stmt::MaterializeTemporaryExprClass:
7989  if (const Expr *Result =
7990  EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7991  refVars, ParentDecl))
7992  return Result;
7993  return E;
7994 
7995  // Everything else: we simply don't reason about them.
7996  default:
7997  return nullptr;
7998  }
7999 }
8000 
8001 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
8002 /// See the comments for EvalAddr for more details.
8003 static const Expr *EvalVal(const Expr *E,
8004  SmallVectorImpl<const DeclRefExpr *> &refVars,
8005  const Decl *ParentDecl) {
8006  do {
8007  // We should only be called for evaluating non-pointer expressions, or
8008  // expressions with a pointer type that are not used as references but
8009  // instead
8010  // are l-values (e.g., DeclRefExpr with a pointer type).
8011 
8012  // Our "symbolic interpreter" is just a dispatch off the currently
8013  // viewed AST node. We then recursively traverse the AST by calling
8014  // EvalAddr and EvalVal appropriately.
8015 
8016  E = E->IgnoreParens();
8017  switch (E->getStmtClass()) {
8018  case Stmt::ImplicitCastExprClass: {
8019  const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8020  if (IE->getValueKind() == VK_LValue) {
8021  E = IE->getSubExpr();
8022  continue;
8023  }
8024  return nullptr;
8025  }
8026 
8027  case Stmt::ExprWithCleanupsClass:
8028  return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8029  ParentDecl);
8030 
8031  case Stmt::DeclRefExprClass: {
8032  // When we hit a DeclRefExpr we are looking at code that refers to a
8033  // variable's name. If it's not a reference variable we check if it has
8034  // local storage within the function, and if so, return the expression.
8035  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8036 
8037  // If we leave the immediate function, the lifetime isn't about to end.
8039  return nullptr;
8040 
8041  if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8042  // Check if it refers to itself, e.g. "int& i = i;".
8043  if (V == ParentDecl)
8044  return DR;
8045 
8046  if (V->hasLocalStorage()) {
8047  if (!V->getType()->isReferenceType())
8048  return DR;
8049 
8050  // Reference variable, follow through to the expression that
8051  // it points to.
8052  if (V->hasInit()) {
8053  // Add the reference variable to the "trail".
8054  refVars.push_back(DR);
8055  return EvalVal(V->getInit(), refVars, V);
8056  }
8057  }
8058  }
8059 
8060  return nullptr;
8061  }
8062 
8063  case Stmt::UnaryOperatorClass: {
8064  // The only unary operator that make sense to handle here
8065  // is Deref. All others don't resolve to a "name." This includes
8066  // handling all sorts of rvalues passed to a unary operator.
8067  const UnaryOperator *U = cast<UnaryOperator>(E);
8068 
8069  if (U->getOpcode() == UO_Deref)
8070  return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8071 
8072  return nullptr;
8073  }
8074 
8075  case Stmt::ArraySubscriptExprClass: {
8076  // Array subscripts are potential references to data on the stack. We
8077  // retrieve the DeclRefExpr* for the array variable if it indeed
8078  // has local storage.
8079  const auto *ASE = cast<ArraySubscriptExpr>(E);
8080  if (ASE->isTypeDependent())
8081  return nullptr;
8082  return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8083  }
8084 
8085  case Stmt::OMPArraySectionExprClass: {
8086  return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8087  ParentDecl);
8088  }
8089 
8090  case Stmt::ConditionalOperatorClass: {
8091  // For conditional operators we need to see if either the LHS or RHS are
8092  // non-NULL Expr's. If one is non-NULL, we return it.
8093  const ConditionalOperator *C = cast<ConditionalOperator>(E);
8094 
8095  // Handle the GNU extension for missing LHS.
8096  if (const Expr *LHSExpr = C->getLHS()) {
8097  // In C++, we can have a throw-expression, which has 'void' type.
8098  if (!LHSExpr->getType()->isVoidType())
8099  if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8100  return LHS;
8101  }
8102 
8103  // In C++, we can have a throw-expression, which has 'void' type.
8104  if (C->getRHS()->getType()->isVoidType())
8105  return nullptr;
8106 
8107  return EvalVal(C->getRHS(), refVars, ParentDecl);
8108  }
8109 
8110  // Accesses to members are potential references to data on the stack.
8111  case Stmt::MemberExprClass: {
8112  const MemberExpr *M = cast<MemberExpr>(E);
8113 
8114  // Check for indirect access. We only want direct field accesses.
8115  if (M->isArrow())
8116  return nullptr;
8117 
8118  // Check whether the member type is itself a reference, in which case
8119  // we're not going to refer to the member, but to what the member refers
8120  // to.
8121  if (M->getMemberDecl()->getType()->isReferenceType())
8122  return nullptr;
8123 
8124  return EvalVal(M->getBase(), refVars, ParentDecl);
8125  }
8126 
8127  case Stmt::MaterializeTemporaryExprClass:
8128  if (const Expr *Result =
8129  EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8130  refVars, ParentDecl))
8131  return Result;
8132  return E;
8133 
8134  default:
8135  // Check that we don't return or take the address of a reference to a
8136  // temporary. This is only useful in C++.
8137  if (!E->isTypeDependent() && E->isRValue())
8138  return E;
8139 
8140  // Everything else: we simply don't reason about them.
8141  return nullptr;
8142  }
8143  } while (true);
8144 }
8145 
8146 void
8147 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8148  SourceLocation ReturnLoc,
8149  bool isObjCMethod,
8150  const AttrVec *Attrs,
8151  const FunctionDecl *FD) {
8152  CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8153 
8154  // Check if the return value is null but should not be.
8155  if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8156  (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8157  CheckNonNullExpr(*this, RetValExp))
8158  Diag(ReturnLoc, diag::warn_null_ret)
8159  << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8160 
8161  // C++11 [basic.stc.dynamic.allocation]p4:
8162  // If an allocation function declared with a non-throwing
8163  // exception-specification fails to allocate storage, it shall return
8164  // a null pointer. Any other allocation function that fails to allocate
8165  // storage shall indicate failure only by throwing an exception [...]
8166  if (FD) {
8168  if (Op == OO_New || Op == OO_Array_New) {
8169  const FunctionProtoType *Proto
8170  = FD->getType()->castAs<FunctionProtoType>();
8171  if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8172  CheckNonNullExpr(*this, RetValExp))
8173  Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8174  << FD << getLangOpts().CPlusPlus11;
8175  }
8176  }
8177 }
8178 
8179 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8180 
8181 /// Check for comparisons of floating point operands using != and ==.
8182 /// Issue a warning if these are no self-comparisons, as they are not likely
8183 /// to do what the programmer intended.
8184 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8185  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8186  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8187 
8188  // Special case: check for x == x (which is OK).
8189  // Do not emit warnings for such cases.
8190  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8191  if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8192  if (DRL->getDecl() == DRR->getDecl())
8193  return;
8194 
8195  // Special case: check for comparisons against literals that can be exactly
8196  // represented by APFloat. In such cases, do not emit a warning. This
8197  // is a heuristic: often comparison against such literals are used to
8198  // detect if a value in a variable has not changed. This clearly can
8199  // lead to false negatives.
8200  if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8201  if (FLL->isExact())
8202  return;
8203  } else
8204  if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8205  if (FLR->isExact())
8206  return;
8207 
8208  // Check for comparisons with builtin types.
8209  if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8210  if (CL->getBuiltinCallee())
8211  return;
8212 
8213  if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8214  if (CR->getBuiltinCallee())
8215  return;
8216 
8217  // Emit the diagnostic.
8218  Diag(Loc, diag::warn_floatingpoint_eq)
8219  << LHS->getSourceRange() << RHS->getSourceRange();
8220 }
8221 
8222 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8223 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8224 
8225 namespace {
8226 
8227 /// Structure recording the 'active' range of an integer-valued
8228 /// expression.
8229 struct IntRange {
8230  /// The number of bits active in the int.
8231  unsigned Width;
8232 
8233  /// True if the int is known not to have negative values.
8234  bool NonNegative;
8235 
8236  IntRange(unsigned Width, bool NonNegative)
8237  : Width(Width), NonNegative(NonNegative) {}
8238 
8239  /// Returns the range of the bool type.
8240  static IntRange forBoolType() {
8241  return IntRange(1, true);
8242  }
8243 
8244  /// Returns the range of an opaque value of the given integral type.
8245  static IntRange forValueOfType(ASTContext &C, QualType T) {
8246  return forValueOfCanonicalType(C,
8248  }
8249 
8250  /// Returns the range of an opaque value of a canonical integral type.
8251  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8252  assert(T->isCanonicalUnqualified());
8253 
8254  if (const VectorType *VT = dyn_cast<VectorType>(T))
8255  T = VT->getElementType().getTypePtr();
8256  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8257  T = CT->getElementType().getTypePtr();
8258  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8259  T = AT->getValueType().getTypePtr();
8260 
8261  if (!C.getLangOpts().CPlusPlus) {
8262  // For enum types in C code, use the underlying datatype.
8263  if (const EnumType *ET = dyn_cast<EnumType>(T))
8264  T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8265  } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8266  // For enum types in C++, use the known bit width of the enumerators.
8267  EnumDecl *Enum = ET->getDecl();
8268  // In C++11, enums can have a fixed underlying type. Use this type to
8269  // compute the range.
8270  if (Enum->isFixed()) {
8271  return IntRange(C.getIntWidth(QualType(T, 0)),
8272  !ET->isSignedIntegerOrEnumerationType());
8273  }
8274 
8275  unsigned NumPositive = Enum->getNumPositiveBits();
8276  unsigned NumNegative = Enum->getNumNegativeBits();
8277 
8278  if (NumNegative == 0)
8279  return IntRange(NumPositive, true/*NonNegative*/);
8280  else
8281  return IntRange(std::max(NumPositive + 1, NumNegative),
8282  false/*NonNegative*/);
8283  }
8284 
8285  const BuiltinType *BT = cast<BuiltinType>(T);
8286  assert(BT->isInteger());
8287 
8288  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8289  }
8290 
8291  /// Returns the "target" range of a canonical integral type, i.e.
8292  /// the range of values expressible in the type.
8293  ///
8294  /// This matches forValueOfCanonicalType except that enums have the
8295  /// full range of their type, not the range of their enumerators.
8296  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8297  assert(T->isCanonicalUnqualified());
8298 
8299  if (const VectorType *VT = dyn_cast<VectorType>(T))
8300  T = VT->getElementType().getTypePtr();
8301  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8302  T = CT->getElementType().getTypePtr();
8303  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8304  T = AT->getValueType().getTypePtr();
8305  if (const EnumType *ET = dyn_cast<EnumType>(T))
8306  T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8307 
8308  const BuiltinType *BT = cast<BuiltinType>(T);
8309  assert(BT->isInteger());
8310 
8311  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8312  }
8313 
8314  /// Returns the supremum of two ranges: i.e. their conservative merge.
8315  static IntRange join(IntRange L, IntRange R) {
8316  return IntRange(std::max(L.Width, R.Width),
8317  L.NonNegative && R.NonNegative);
8318  }
8319 
8320  /// Returns the infinum of two ranges: i.e. their aggressive merge.
8321  static IntRange meet(IntRange L, IntRange R) {
8322  return IntRange(std::min(L.Width, R.Width),
8323  L.NonNegative || R.NonNegative);
8324  }
8325 };
8326 
8327 } // namespace
8328 
8329 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8330  unsigned MaxWidth) {
8331  if (value.isSigned() && value.isNegative())
8332  return IntRange(value.getMinSignedBits(), false);
8333 
8334  if (value.getBitWidth() > MaxWidth)
8335  value = value.trunc(MaxWidth);
8336 
8337  // isNonNegative() just checks the sign bit without considering
8338  // signedness.
8339  return IntRange(value.getActiveBits(), true);
8340 }
8341 
8342 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8343  unsigned MaxWidth) {
8344  if (result.isInt())
8345  return GetValueRange(C, result.getInt(), MaxWidth);
8346 
8347  if (result.isVector()) {
8348  IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8349  for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8350  IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8351  R = IntRange::join(R, El);
8352  }
8353  return R;
8354  }
8355 
8356  if (result.isComplexInt()) {
8357  IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8358  IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8359  return IntRange::join(R, I);
8360  }
8361 
8362  // This can happen with lossless casts to intptr_t of "based" lvalues.
8363  // Assume it might use arbitrary bits.
8364  // FIXME: The only reason we need to pass the type in here is to get
8365  // the sign right on this one case. It would be nice if APValue
8366  // preserved this.
8367  assert(result.isLValue() || result.isAddrLabelDiff());
8368  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8369 }
8370 
8371 static QualType GetExprType(const Expr *E) {
8372  QualType Ty = E->getType();
8373  if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8374  Ty = AtomicRHS->getValueType();
8375  return Ty;
8376 }
8377 
8378 /// Pseudo-evaluate the given integer expression, estimating the
8379 /// range of values it might take.
8380 ///
8381 /// \param MaxWidth - the width to which the value will be truncated
8382 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8383  E = E->IgnoreParens();
8384 
8385  // Try a full evaluation first.
8386  Expr::EvalResult result;
8387  if (E->EvaluateAsRValue(result, C))
8388  return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8389 
8390  // I think we only want to look through implicit casts here; if the
8391  // user has an explicit widening cast, we should treat the value as
8392  // being of the new, wider type.
8393  if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8394  if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8395  return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8396 
8397  IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8398 
8399  bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8400  CE->getCastKind() == CK_BooleanToSignedIntegral;
8401 
8402  // Assume that non-integer casts can span the full range of the type.
8403  if (!isIntegerCast)
8404  return OutputTypeRange;
8405 
8406  IntRange SubRange
8407  = GetExprRange(C, CE->getSubExpr(),
8408  std::min(MaxWidth, OutputTypeRange.Width));
8409 
8410  // Bail out if the subexpr's range is as wide as the cast type.
8411  if (SubRange.Width >= OutputTypeRange.Width)
8412  return OutputTypeRange;
8413 
8414  // Otherwise, we take the smaller width, and we're non-negative if
8415  // either the output type or the subexpr is.
8416  return IntRange(SubRange.Width,
8417  SubRange.NonNegative || OutputTypeRange.NonNegative);
8418  }
8419 
8420  if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8421  // If we can fold the condition, just take that operand.
8422  bool CondResult;
8423  if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8424  return GetExprRange(C, CondResult ? CO->getTrueExpr()
8425  : CO->getFalseExpr(),
8426  MaxWidth);
8427 
8428  // Otherwise, conservatively merge.
8429  IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8430  IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8431  return IntRange::join(L, R);
8432  }
8433 
8434  if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8435  switch (BO->getOpcode()) {
8436  case BO_Cmp:
8437  llvm_unreachable("builtin <=> should have class type");
8438 
8439  // Boolean-valued operations are single-bit and positive.
8440  case BO_LAnd:
8441  case BO_LOr:
8442  case BO_LT:
8443  case BO_GT:
8444  case BO_LE:
8445  case BO_GE:
8446  case BO_EQ:
8447  case BO_NE:
8448  return IntRange::forBoolType();
8449 
8450  // The type of the assignments is the type of the LHS, so the RHS
8451  // is not necessarily the same type.
8452  case BO_MulAssign:
8453  case BO_DivAssign:
8454  case BO_RemAssign:
8455  case BO_AddAssign:
8456  case BO_SubAssign:
8457  case BO_XorAssign:
8458  case BO_OrAssign:
8459  // TODO: bitfields?
8460  return IntRange::forValueOfType(C, GetExprType(E));
8461 
8462  // Simple assignments just pass through the RHS, which will have
8463  // been coerced to the LHS type.
8464  case BO_Assign:
8465  // TODO: bitfields?
8466  return GetExprRange(C, BO->getRHS(), MaxWidth);
8467 
8468  // Operations with opaque sources are black-listed.
8469  case BO_PtrMemD:
8470  case BO_PtrMemI:
8471  return IntRange::forValueOfType(C, GetExprType(E));
8472 
8473  // Bitwise-and uses the *infinum* of the two source ranges.
8474  case BO_And:
8475  case BO_AndAssign:
8476  return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8477  GetExprRange(C, BO->getRHS(), MaxWidth));
8478 
8479  // Left shift gets black-listed based on a judgement call.
8480  case BO_Shl:
8481  // ...except that we want to treat '1 << (blah)' as logically
8482  // positive. It's an important idiom.
8483  if (IntegerLiteral *I
8484  = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8485  if (I->getValue() == 1) {
8486  IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8487  return IntRange(R.Width, /*NonNegative*/ true);
8488  }
8489  }
8490  LLVM_FALLTHROUGH;
8491 
8492  case BO_ShlAssign:
8493  return IntRange::forValueOfType(C, GetExprType(E));
8494 
8495  // Right shift by a constant can narrow its left argument.
8496  case BO_Shr:
8497  case BO_ShrAssign: {
8498  IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8499 
8500  // If the shift amount is a positive constant, drop the width by
8501  // that much.
8502  llvm::APSInt shift;
8503  if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8504  shift.isNonNegative()) {
8505  unsigned zext = shift.getZExtValue();
8506  if (zext >= L.Width)
8507  L.Width = (L.NonNegative ? 0 : 1);
8508  else
8509  L.Width -= zext;
8510  }
8511 
8512  return L;
8513  }
8514 
8515  // Comma acts as its right operand.
8516  case BO_Comma:
8517  return GetExprRange(C, BO->getRHS(), MaxWidth);
8518 
8519  // Black-list pointer subtractions.
8520  case BO_Sub:
8521  if (BO->getLHS()->getType()->isPointerType())
8522  return IntRange::forValueOfType(C, GetExprType(E));
8523  break;
8524 
8525  // The width of a division result is mostly determined by the size
8526  // of the LHS.
8527  case BO_Div: {
8528  // Don't 'pre-truncate' the operands.
8529  unsigned opWidth = C.getIntWidth(GetExprType(E));
8530  IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8531 
8532  // If the divisor is constant, use that.
8533  llvm::APSInt divisor;
8534  if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8535  unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8536  if (log2 >= L.Width)
8537  L.Width = (L.NonNegative ? 0 : 1);
8538  else
8539  L.Width = std::min(L.Width - log2, MaxWidth);
8540  return L;
8541  }
8542 
8543  // Otherwise, just use the LHS's width.
8544  IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8545  return IntRange(L.Width, L.NonNegative && R.NonNegative);
8546  }
8547 
8548  // The result of a remainder can't be larger than the result of
8549  // either side.
8550  case BO_Rem: {
8551  // Don't 'pre-truncate' the operands.
8552  unsigned opWidth = C.getIntWidth(GetExprType(E));
8553  IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8554  IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8555 
8556  IntRange meet = IntRange::meet(L, R);
8557  meet.Width = std::min(meet.Width, MaxWidth);
8558  return meet;
8559  }
8560 
8561  // The default behavior is okay for these.
8562  case BO_Mul:
8563  case BO_Add:
8564  case BO_Xor:
8565  case BO_Or:
8566  break;
8567  }
8568 
8569  // The default case is to treat the operation as if it were closed
8570  // on the narrowest type that encompasses both operands.
8571  IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8572  IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8573  return IntRange::join(L, R);
8574  }
8575 
8576  if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8577  switch (UO->getOpcode()) {
8578  // Boolean-valued operations are white-listed.
8579  case UO_LNot:
8580  return IntRange::forBoolType();
8581 
8582  // Operations with opaque sources are black-listed.
8583  case UO_Deref:
8584  case UO_AddrOf: // should be impossible
8585  return IntRange::forValueOfType(C, GetExprType(E));
8586 
8587  default:
8588  return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8589  }
8590  }
8591 
8592  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8593  return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8594 
8595  if (const auto *BitField = E->getSourceBitField())
8596  return IntRange(BitField->getBitWidthValue(C),
8597  BitField->getType()->isUnsignedIntegerOrEnumerationType());
8598 
8599  return IntRange::forValueOfType(C, GetExprType(E));
8600 }
8601 
8602 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
8603  return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8604 }
8605 
8606 /// Checks whether the given value, which currently has the given
8607 /// source semantics, has the same value when coerced through the
8608 /// target semantics.
8609 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8610  const llvm::fltSemantics &Src,
8611  const llvm::fltSemantics &Tgt) {
8612  llvm::APFloat truncated = value;
8613 
8614  bool ignored;
8615  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8616  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8617 
8618  return truncated.bitwiseIsEqual(value);
8619 }
8620 
8621 /// Checks whether the given value, which currently has the given
8622 /// source semantics, has the same value when coerced through the
8623 /// target semantics.
8624 ///
8625 /// The value might be a vector of floats (or a complex number).
8626 static bool IsSameFloatAfterCast(const APValue &value,
8627  const llvm::fltSemantics &Src,
8628  const llvm::fltSemantics &Tgt) {
8629  if (value.isFloat())
8630  return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8631 
8632  if (value.isVector()) {
8633  for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8634  if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8635  return false;
8636  return true;
8637  }
8638 
8639  assert(value.isComplexFloat());
8640  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8641  IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8642 }
8643 
8644 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8645 
8646 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8647  // Suppress cases where we are comparing against an enum constant.
8648  if (const DeclRefExpr *DR =
8649  dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8650  if (isa<EnumConstantDecl>(DR->getDecl()))
8651  return true;
8652 
8653  // Suppress cases where the '0' value is expanded from a macro.
8654  if (E->getLocStart().isMacroID())
8655  return true;
8656 
8657  return false;
8658 }
8659 
8661  return E->getType()->isIntegerType() &&
8662  (!E->getType()->isSignedIntegerType() ||
8664 }
8665 
8666 namespace {
8667 /// The promoted range of values of a type. In general this has the
8668 /// following structure:
8669 ///
8670 /// |-----------| . . . |-----------|
8671 /// ^ ^ ^ ^
8672 /// Min HoleMin HoleMax Max
8673 ///
8674 /// ... where there is only a hole if a signed type is promoted to unsigned
8675 /// (in which case Min and Max are the smallest and largest representable
8676 /// values).
8677 struct PromotedRange {
8678  // Min, or HoleMax if there is a hole.
8679  llvm::APSInt PromotedMin;
8680  // Max, or HoleMin if there is a hole.
8681  llvm::APSInt PromotedMax;
8682 
8683  PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8684  if (R.Width == 0)
8685  PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8686  else if (R.Width >= BitWidth && !Unsigned) {
8687  // Promotion made the type *narrower*. This happens when promoting
8688  // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8689  // Treat all values of 'signed int' as being in range for now.
8690  PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8691  PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8692  } else {
8693  PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8694  .extOrTrunc(BitWidth);
8695  PromotedMin.setIsUnsigned(Unsigned);
8696 
8697  PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8698  .extOrTrunc(BitWidth);
8699  PromotedMax.setIsUnsigned(Unsigned);
8700  }
8701  }
8702 
8703  // Determine whether this range is contiguous (has no hole).
8704  bool isContiguous() const { return PromotedMin <= PromotedMax; }
8705 
8706  // Where a constant value is within the range.
8707  enum ComparisonResult {
8708  LT = 0x1,
8709  LE = 0x2,
8710  GT = 0x4,
8711  GE = 0x8,
8712  EQ = 0x10,
8713  NE = 0x20,
8714  InRangeFlag = 0x40,
8715 
8716  Less = LE | LT | NE,
8717  Min = LE | InRangeFlag,
8718  InRange = InRangeFlag,
8719  Max = GE | InRangeFlag,
8720  Greater = GE | GT | NE,
8721 
8722  OnlyValue = LE | GE | EQ | InRangeFlag,
8723  InHole = NE
8724  };
8725 
8726  ComparisonResult compare(const llvm::APSInt &Value) const {
8727  assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8728  Value.isUnsigned() == PromotedMin.isUnsigned());
8729  if (!isContiguous()) {
8730  assert(Value.isUnsigned() && "discontiguous range for signed compare");
8731  if (Value.isMinValue()) return Min;
8732  if (Value.isMaxValue()) return Max;
8733  if (Value >= PromotedMin) return InRange;
8734  if (Value <= PromotedMax) return InRange;
8735  return InHole;
8736  }
8737 
8738  switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8739  case -1: return Less;
8740  case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8741  case 1:
8742  switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8743  case -1: return InRange;
8744  case 0: return Max;
8745  case 1: return Greater;
8746  }
8747  }
8748 
8749  llvm_unreachable("impossible compare result");
8750  }
8751 
8753  constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8754  if (Op == BO_Cmp) {
8755  ComparisonResult LTFlag = LT, GTFlag = GT;
8756  if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8757 
8758  if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8759  if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8760  if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8761  return llvm::None;
8762  }
8763 
8764  ComparisonResult TrueFlag, FalseFlag;
8765  if (Op == BO_EQ) {
8766  TrueFlag = EQ;
8767  FalseFlag = NE;
8768  } else if (Op == BO_NE) {
8769  TrueFlag = NE;
8770  FalseFlag = EQ;
8771  } else {
8772  if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8773  TrueFlag = LT;
8774  FalseFlag = GE;
8775  } else {
8776  TrueFlag = GT;
8777  FalseFlag = LE;
8778  }
8779  if (Op == BO_GE || Op == BO_LE)
8780  std::swap(TrueFlag, FalseFlag);
8781  }
8782  if (R & TrueFlag)
8783  return StringRef("true");
8784  if (R & FalseFlag)
8785  return StringRef("false");
8786  return llvm::None;
8787  }
8788 };
8789 }
8790 
8791 static bool HasEnumType(Expr *E) {
8792  // Strip off implicit integral promotions.
8793  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8794  if (ICE->getCastKind() != CK_IntegralCast &&
8795  ICE->getCastKind() != CK_NoOp)
8796  break;
8797  E = ICE->getSubExpr();
8798  }
8799 
8800  return E->getType()->isEnumeralType();
8801 }
8802 
8803 static int classifyConstantValue(Expr *Constant) {
8804  // The values of this enumeration are used in the diagnostics
8805  // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8806  enum ConstantValueKind {
8807  Miscellaneous = 0,
8808  LiteralTrue,
8809  LiteralFalse
8810  };
8811  if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8812  return BL->getValue() ? ConstantValueKind::LiteralTrue
8813  : ConstantValueKind::LiteralFalse;
8814  return ConstantValueKind::Miscellaneous;
8815 }
8816 
8818  Expr *Constant, Expr *Other,
8819  const llvm::APSInt &Value,
8820  bool RhsConstant) {
8821  if (S.inTemplateInstantiation())
8822  return false;
8823 
8824  Expr *OriginalOther = Other;
8825 
8826  Constant = Constant->IgnoreParenImpCasts();
8827  Other = Other->IgnoreParenImpCasts();
8828 
8829  // Suppress warnings on tautological comparisons between values of the same
8830  // enumeration type. There are only two ways we could warn on this:
8831  // - If the constant is outside the range of representable values of
8832  // the enumeration. In such a case, we should warn about the cast
8833  // to enumeration type, not about the comparison.
8834  // - If the constant is the maximum / minimum in-range value. For an
8835  // enumeratin type, such comparisons can be meaningful and useful.
8836  if (Constant->getType()->isEnumeralType() &&
8837  S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8838  return false;
8839 
8840  // TODO: Investigate using GetExprRange() to get tighter bounds
8841  // on the bit ranges.
8842  QualType OtherT = Other->getType();
8843  if (const auto *AT = OtherT->getAs<AtomicType>())
8844  OtherT = AT->getValueType();
8845  IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8846 
8847  // Whether we're treating Other as being a bool because of the form of
8848  // expression despite it having another type (typically 'int' in C).
8849  bool OtherIsBooleanDespiteType =
8850  !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8851  if (OtherIsBooleanDespiteType)
8852  OtherRange = IntRange::forBoolType();
8853 
8854  // Determine the promoted range of the other type and see if a comparison of
8855  // the constant against that range is tautological.
8856  PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8857  Value.isUnsigned());
8858  auto Cmp = OtherPromotedRange.compare(Value);
8859  auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8860  if (!Result)
8861  return false;
8862 
8863  // Suppress the diagnostic for an in-range comparison if the constant comes
8864  // from a macro or enumerator. We don't want to diagnose
8865  //
8866  // some_long_value <= INT_MAX
8867  //
8868  // when sizeof(int) == sizeof(long).
8869  bool InRange = Cmp & PromotedRange::InRangeFlag;
8870  if (InRange && IsEnumConstOrFromMacro(S, Constant))
8871  return false;
8872 
8873  // If this is a comparison to an enum constant, include that
8874  // constant in the diagnostic.
8875  const EnumConstantDecl *ED = nullptr;
8876  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8877  ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8878 
8879  // Should be enough for uint128 (39 decimal digits)
8880  SmallString<64> PrettySourceValue;
8881  llvm::raw_svector_ostream OS(PrettySourceValue);
8882  if (ED)
8883  OS << '\'' << *ED << "' (" << Value << ")";
8884  else
8885  OS << Value;
8886 
8887  // FIXME: We use a somewhat different formatting for the in-range cases and
8888  // cases involving boolean values for historical reasons. We should pick a
8889  // consistent way of presenting these diagnostics.
8890  if (!InRange || Other->isKnownToHaveBooleanValue()) {
8892  E->getOperatorLoc(), E,
8893  S.PDiag(!InRange ? diag::warn_out_of_range_compare
8894  : diag::warn_tautological_bool_compare)
8895  << OS.str() << classifyConstantValue(Constant)
8896  << OtherT << OtherIsBooleanDespiteType << *Result
8897  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8898  } else {
8899  unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8900  ? (HasEnumType(OriginalOther)
8901  ? diag::warn_unsigned_enum_always_true_comparison
8902  : diag::warn_unsigned_always_true_comparison)
8903  : diag::warn_tautological_constant_compare;
8904 
8905  S.Diag(E->getOperatorLoc(), Diag)
8906  << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8907  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8908  }
8909 
8910  return true;
8911 }
8912 
8913 /// Analyze the operands of the given comparison. Implements the
8914 /// fallback case from AnalyzeComparison.
8918 }
8919 
8920 /// \brief Implements -Wsign-compare.
8921 ///
8922 /// \param E the binary operator to check for warnings
8924  // The type the comparison is being performed in.
8925  QualType T = E->getLHS()->getType();
8926 
8927  // Only analyze comparison operators where both sides have been converted to
8928  // the same type.
8929  if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8930  return AnalyzeImpConvsInComparison(S, E);
8931 
8932  // Don't analyze value-dependent comparisons directly.
8933  if (E->isValueDependent())
8934  return AnalyzeImpConvsInComparison(S, E);
8935 
8936  Expr *LHS = E->getLHS();
8937  Expr *RHS = E->getRHS();
8938 
8939  if (T->isIntegralType(S.Context)) {
8940  llvm::APSInt RHSValue;
8941  llvm::APSInt LHSValue;
8942 
8943  bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8944  bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
8945 
8946  // We don't care about expressions whose result is a constant.
8947  if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8948  return AnalyzeImpConvsInComparison(S, E);
8949 
8950  // We only care about expressions where just one side is literal
8951  if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8952  // Is the constant on the RHS or LHS?
8953  const bool RhsConstant = IsRHSIntegralLiteral;
8954  Expr *Const = RhsConstant ? RHS : LHS;
8955  Expr *Other = RhsConstant ? LHS : RHS;
8956  const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8957 
8958  // Check whether an integer constant comparison results in a value
8959  // of 'true' or 'false'.
8960  if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8961  return AnalyzeImpConvsInComparison(S, E);
8962  }
8963  }
8964 
8966  // We don't do anything special if this isn't an unsigned integral
8967  // comparison: we're only interested in integral comparisons, and
8968  // signed comparisons only happen in cases we don't care to warn about.
8969  return AnalyzeImpConvsInComparison(S, E);
8970  }
8971 
8972  LHS = LHS->IgnoreParenImpCasts();
8973  RHS = RHS->IgnoreParenImpCasts();
8974 
8975  // Check to see if one of the (unmodified) operands is of different
8976  // signedness.
8977  Expr *signedOperand, *unsignedOperand;
8978  if (LHS->getType()->hasSignedIntegerRepresentation()) {
8979  assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8980  "unsigned comparison between two signed integer expressions?");
8981  signedOperand = LHS;
8982  unsignedOperand = RHS;
8983  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8984  signedOperand = RHS;
8985  unsignedOperand = LHS;
8986  } else {
8987  return AnalyzeImpConvsInComparison(S, E);
8988  }
8989 
8990  // Otherwise, calculate the effective range of the signed operand.
8991  IntRange signedRange = GetExprRange(S.Context, signedOperand);
8992 
8993  // Go ahead and analyze implicit conversions in the operands. Note
8994  // that we skip the implicit conversions on both sides.
8997 
8998  // If the signed range is non-negative, -Wsign-compare won't fire.
8999  if (signedRange.NonNegative)
9000  return;
9001 
9002  // For (in)equality comparisons, if the unsigned operand is a
9003  // constant which cannot collide with a overflowed signed operand,
9004  // then reinterpreting the signed operand as unsigned will not
9005  // change the result of the comparison.
9006  if (E->isEqualityOp()) {
9007  unsigned comparisonWidth = S.Context.getIntWidth(T);
9008  IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9009 
9010  // We should never be unable to prove that the unsigned operand is
9011  // non-negative.
9012  assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9013 
9014  if (unsignedRange.Width < comparisonWidth)
9015  return;
9016  }
9017 
9019  S.PDiag(diag::warn_mixed_sign_comparison)
9020  << LHS->getType() << RHS->getType()
9021  << LHS->getSourceRange() << RHS->getSourceRange());
9022 }
9023 
9024 /// Analyzes an attempt to assign the given value to a bitfield.
9025 ///
9026 /// Returns true if there was something fishy about the attempt.
9027 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9028  SourceLocation InitLoc) {
9029  assert(Bitfield->isBitField());
9030  if (Bitfield->isInvalidDecl())
9031  return false;
9032 
9033  // White-list bool bitfields.
9034  QualType BitfieldType = Bitfield->getType();
9035  if (BitfieldType->isBooleanType())
9036  return false;
9037 
9038  if (BitfieldType->isEnumeralType()) {
9039  EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9040  // If the underlying enum type was not explicitly specified as an unsigned
9041  // type and the enum contain only positive values, MSVC++ will cause an
9042  // inconsistency by storing this as a signed type.
9043  if (S.getLangOpts().CPlusPlus11 &&
9044  !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9045  BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9046  BitfieldEnumDecl->getNumNegativeBits() == 0) {
9047  S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9048  << BitfieldEnumDecl->getNameAsString();
9049  }
9050  }
9051 
9052  if (Bitfield->getType()->isBooleanType())
9053  return false;
9054 
9055  // Ignore value- or type-dependent expressions.
9056  if (Bitfield->getBitWidth()->isValueDependent() ||
9057  Bitfield->getBitWidth()->isTypeDependent() ||
9058  Init->isValueDependent() ||
9059  Init->isTypeDependent())
9060  return false;
9061 
9062  Expr *OriginalInit = Init->IgnoreParenImpCasts();
9063  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9064 
9065  llvm::APSInt Value;
9066  if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9068  // The RHS is not constant. If the RHS has an enum type, make sure the
9069  // bitfield is wide enough to hold all the values of the enum without
9070  // truncation.
9071  if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9072  EnumDecl *ED = EnumTy->getDecl();
9073  bool SignedBitfield = BitfieldType->isSignedIntegerType();
9074 
9075  // Enum types are implicitly signed on Windows, so check if there are any
9076  // negative enumerators to see if the enum was intended to be signed or
9077  // not.
9078  bool SignedEnum = ED->getNumNegativeBits() > 0;
9079 
9080  // Check for surprising sign changes when assigning enum values to a
9081  // bitfield of different signedness. If the bitfield is signed and we
9082  // have exactly the right number of bits to store this unsigned enum,
9083  // suggest changing the enum to an unsigned type. This typically happens
9084  // on Windows where unfixed enums always use an underlying type of 'int'.
9085  unsigned DiagID = 0;
9086  if (SignedEnum && !SignedBitfield) {
9087  DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9088  } else if (SignedBitfield && !SignedEnum &&
9089  ED->getNumPositiveBits() == FieldWidth) {
9090  DiagID = diag::warn_signed_bitfield_enum_conversion;
9091  }
9092 
9093  if (DiagID) {
9094  S.Diag(InitLoc, DiagID) << Bitfield << ED;
9095  TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9096  SourceRange TypeRange =
9097  TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9098  S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9099  << SignedEnum << TypeRange;
9100  }
9101 
9102  // Compute the required bitwidth. If the enum has negative values, we need
9103  // one more bit than the normal number of positive bits to represent the
9104  // sign bit.
9105  unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9106  ED->getNumNegativeBits())
9107  : ED->getNumPositiveBits();
9108 
9109  // Check the bitwidth.
9110  if (BitsNeeded > FieldWidth) {
9111  Expr *WidthExpr = Bitfield->getBitWidth();
9112  S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9113  << Bitfield << ED;
9114  S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9115  << BitsNeeded << ED << WidthExpr->getSourceRange();
9116  }
9117  }
9118 
9119  return false;
9120  }
9121 
9122  unsigned OriginalWidth = Value.getBitWidth();
9123 
9124  if (!Value.isSigned() || Value.isNegative())
9125  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9126  if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9127  OriginalWidth = Value.getMinSignedBits();
9128 
9129  if (OriginalWidth <= FieldWidth)
9130  return false;
9131 
9132  // Compute the value which the bitfield will contain.
9133  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9134  TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9135 
9136  // Check whether the stored value is equal to the original value.
9137  TruncatedValue = TruncatedValue.extend(OriginalWidth);
9138  if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9139  return false;
9140 
9141  // Special-case bitfields of width 1: booleans are naturally 0/1, and
9142  // therefore don't strictly fit into a signed bitfield of width 1.
9143  if (FieldWidth == 1 && Value == 1)
9144  return false;
9145 
9146  std::string PrettyValue = Value.toString(10);
9147  std::string PrettyTrunc = TruncatedValue.toString(10);
9148 
9149  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9150  << PrettyValue << PrettyTrunc << OriginalInit->getType()
9151  << Init->getSourceRange();
9152 
9153  return true;
9154 }
9155 
9156 /// Analyze the given simple or compound assignment for warning-worthy
9157 /// operations.
9159  // Just recurse on the LHS.
9161 
9162  // We want to recurse on the RHS as normal unless we're assigning to
9163  // a bitfield.
9164  if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9165  if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9166  E->getOperatorLoc())) {
9167  // Recurse, ignoring any implicit conversions on the RHS.
9169  E->getOperatorLoc());
9170  }
9171  }
9172 
9174 }
9175 
9176 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
9177 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9178  SourceLocation CContext, unsigned diag,
9179  bool pruneControlFlow = false) {
9180  if (pruneControlFlow) {
9181  S.DiagRuntimeBehavior(E->getExprLoc(), E,
9182  S.PDiag(diag)
9183  << SourceType << T << E->getSourceRange()
9184  << SourceRange(CContext));
9185  return;
9186  }
9187  S.Diag(E->getExprLoc(), diag)
9188  << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9189 }
9190 
9191 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
9192 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9193  SourceLocation CContext,
9194  unsigned diag, bool pruneControlFlow = false) {
9195  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9196 }
9197 
9198 
9199 /// Diagnose an implicit cast from a floating point value to an integer value.
9201  SourceLocation CContext) {
9202  const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9203  const bool PruneWarnings = S.inTemplateInstantiation();
9204 
9205  Expr *InnerE = E->IgnoreParenImpCasts();
9206  // We also want to warn on, e.g., "int i = -1.234"
9207  if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9208  if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9209  InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9210 
9211  const bool IsLiteral =
9212  isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9213 
9214  llvm::APFloat Value(0.0);
9215  bool IsConstant =
9217  if (!IsConstant) {
9218  return DiagnoseImpCast(S, E, T, CContext,
9219  diag::warn_impcast_float_integer, PruneWarnings);
9220  }
9221 
9222  bool isExact = false;
9223 
9224  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9226  if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9227  &isExact) == llvm::APFloat::opOK &&
9228  isExact) {
9229  if (IsLiteral) return;
9230  return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9231  PruneWarnings);
9232  }
9233 
9234  unsigned DiagID = 0;
9235  if (IsLiteral) {
9236  // Warn on floating point literal to integer.
9237  DiagID = diag::warn_impcast_literal_float_to_integer;
9238  } else if (IntegerValue == 0) {
9239  if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9240  return DiagnoseImpCast(S, E, T, CContext,
9241  diag::warn_impcast_float_integer, PruneWarnings);
9242  }
9243  // Warn on non-zero to zero conversion.
9244  DiagID = diag::warn_impcast_float_to_integer_zero;
9245  } else {
9246  if (IntegerValue.isUnsigned()) {
9247  if (!IntegerValue.isMaxValue()) {
9248  return DiagnoseImpCast(S, E, T, CContext,
9249  diag::warn_impcast_float_integer, PruneWarnings);
9250  }
9251  } else { // IntegerValue.isSigned()
9252  if (!IntegerValue.isMaxSignedValue() &&
9253  !IntegerValue.isMinSignedValue()) {
9254  return DiagnoseImpCast(S, E, T, CContext,
9255  diag::warn_impcast_float_integer, PruneWarnings);
9256  }
9257  }
9258  // Warn on evaluatable floating point expression to integer conversion.
9259  DiagID = diag::warn_impcast_float_to_integer;
9260  }
9261 
9262  // FIXME: Force the precision of the source value down so we don't print
9263  // digits which are usually useless (we don't really care here if we
9264  // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9265  // would automatically print the shortest representation, but it's a bit
9266  // tricky to implement.
9267  SmallString<16> PrettySourceValue;
9268  unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9269  precision = (precision * 59 + 195) / 196;
9270  Value.toString(PrettySourceValue, precision);
9271 
9272  SmallString<16> PrettyTargetValue;
9273  if (IsBool)
9274  PrettyTargetValue = Value.isZero() ? "false" : "true";
9275  else
9276  IntegerValue.toString(PrettyTargetValue);
9277 
9278  if (PruneWarnings) {
9279  S.DiagRuntimeBehavior(E->getExprLoc(), E,
9280  S.PDiag(DiagID)
9281  << E->getType() << T.getUnqualifiedType()
9282  << PrettySourceValue << PrettyTargetValue
9283  << E->getSourceRange() << SourceRange(CContext));
9284  } else {
9285  S.Diag(E->getExprLoc(), DiagID)
9286  << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9287  << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9288  }
9289 }
9290 
9291 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9292  IntRange Range) {
9293  if (!Range.Width) return "0";
9294 
9295  llvm::APSInt ValueInRange = Value;
9296  ValueInRange.setIsSigned(!Range.NonNegative);
9297  ValueInRange = ValueInRange.trunc(Range.Width);
9298  return ValueInRange.toString(10);
9299 }
9300 
9301 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9302  if (!isa<ImplicitCastExpr>(Ex))
9303  return false;
9304 
9305  Expr *InnerE = Ex->IgnoreParenImpCasts();
9306  const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9307  const Type *Source =
9308  S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9309  if (Target->isDependentType())
9310  return false;
9311 
9312  const BuiltinType *FloatCandidateBT =
9313  dyn_cast<BuiltinType>(ToBool ? Source : Target);
9314  const Type *BoolCandidateType = ToBool ? Target : Source;
9315 
9316  return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9317  FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9318 }
9319 
9321  SourceLocation CC) {
9322  unsigned NumArgs = TheCall->getNumArgs();
9323  for (unsigned i = 0; i < NumArgs; ++i) {
9324  Expr *CurrA = TheCall->getArg(i);
9325  if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9326  continue;
9327 
9328  bool IsSwapped = ((i > 0) &&
9329  IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9330  IsSwapped |= ((i < (NumArgs - 1)) &&
9331  IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9332  if (IsSwapped) {
9333  // Warn on this floating-point to bool conversion.
9335  CurrA->getType(), CC,
9336  diag::warn_impcast_floating_point_to_bool);
9337  }
9338  }
9339 }
9340 
9342  SourceLocation CC) {
9343  if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9344  E->getExprLoc()))
9345  return;
9346 
9347  // Don't warn on functions which have return type nullptr_t.
9348  if (isa<CallExpr>(E))
9349  return;
9350 
9351  // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9352  const Expr::NullPointerConstantKind NullKind =
9354  if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9355  return;
9356 
9357  // Return if target type is a safe conversion.
9358  if (T->isAnyPointerType() || T->isBlockPointerType() ||
9359  T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9360  return;
9361 
9362  SourceLocation Loc = E->getSourceRange().getBegin();
9363 
9364  // Venture through the macro stacks to get to the source of macro arguments.
9365  // The new location is a better location than the complete location that was
9366  // passed in.
9367  while (S.SourceMgr.isMacroArgExpansion(Loc))
9369 
9370  while (S.SourceMgr.isMacroArgExpansion(CC))
9372 
9373  // __null is usually wrapped in a macro. Go up a macro if that is the case.
9374  if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9375  StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9376  Loc, S.SourceMgr, S.getLangOpts());
9377  if (MacroName == "NULL")
9378  Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9379  }
9380 
9381  // Only warn if the null and context location are in the same macro expansion.
9382  if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9383  return;
9384 
9385  S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9386  << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
9388  S.getFixItZeroLiteralForType(T, Loc));
9389 }
9390 
9391 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9392  ObjCArrayLiteral *ArrayLiteral);
9393 
9394 static void
9396  ObjCDictionaryLiteral *DictionaryLiteral);
9397 
9398 /// Check a single element within a collection literal against the
9399 /// target element type.
9401  QualType TargetElementType,
9402  Expr *Element,
9403  unsigned ElementKind) {
9404  // Skip a bitcast to 'id' or qualified 'id'.
9405  if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9406  if (ICE->getCastKind() == CK_BitCast &&
9407  ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9408  Element = ICE->getSubExpr();
9409  }
9410 
9411  QualType ElementType = Element->getType();
9412  ExprResult ElementResult(Element);
9413  if (ElementType->getAs<ObjCObjectPointerType>() &&
9414  S.CheckSingleAssignmentConstraints(TargetElementType,
9415  ElementResult,
9416  false, false)
9417  != Sema::Compatible) {
9418  S.Diag(Element->getLocStart(),
9419  diag::warn_objc_collection_literal_element)
9420  << ElementType << ElementKind << TargetElementType
9421  << Element->getSourceRange();
9422  }
9423 
9424  if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9425  checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9426  else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9427  checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9428 }
9429 
9430 /// Check an Objective-C array literal being converted to the given
9431 /// target type.
9432 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9433  ObjCArrayLiteral *ArrayLiteral) {
9434  if (!S.NSArrayDecl)
9435  return;
9436 
9437  const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9438  if (!TargetObjCPtr)
9439  return;
9440 
9441  if (TargetObjCPtr->isUnspecialized() ||
9442  TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9443  != S.NSArrayDecl->getCanonicalDecl())
9444  return;
9445 
9446  auto TypeArgs = TargetObjCPtr->getTypeArgs();
9447  if (TypeArgs.size() != 1)
9448  return;
9449 
9450  QualType TargetElementType = TypeArgs[0];
9451  for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9452  checkObjCCollectionLiteralElement(S, TargetElementType,
9453  ArrayLiteral->getElement(I),
9454  0);
9455  }
9456 }
9457 
9458 /// Check an Objective-C dictionary literal being converted to the given
9459 /// target type.
9460 static void
9462  ObjCDictionaryLiteral *DictionaryLiteral) {
9463  if (!S.NSDictionaryDecl)
9464  return;
9465 
9466  const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9467  if (!TargetObjCPtr)
9468  return;
9469 
9470  if (TargetObjCPtr->isUnspecialized() ||
9471  TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9473  return;
9474 
9475  auto TypeArgs = TargetObjCPtr->getTypeArgs();
9476  if (TypeArgs.size() != 2)
9477  return;
9478 
9479  QualType TargetKeyType = TypeArgs[0];
9480  QualType TargetObjectType = TypeArgs[1];
9481  for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9482  auto Element = DictionaryLiteral->getKeyValueElement(I);
9483  checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9484  checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9485  }
9486 }
9487 
9488 // Helper function to filter out cases for constant width constant conversion.
9489 // Don't warn on char array initialization or for non-decimal values.
9491  SourceLocation CC) {
9492  // If initializing from a constant, and the constant starts with '0',
9493  // then it is a binary, octal, or hexadecimal. Allow these constants
9494  // to fill all the bits, even if there is a sign change.
9495  if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9496  const char FirstLiteralCharacter =
9497  S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9498  if (FirstLiteralCharacter == '0')
9499  return false;
9500  }
9501 
9502  // If the CC location points to a '{', and the type is char, then assume
9503  // assume it is an array initialization.
9504  if (CC.isValid() && T->isCharType()) {
9505  const char FirstContextCharacter =
9507  if (FirstContextCharacter == '{')
9508  return false;
9509  }
9510 
9511  return true;
9512 }
9513 
9514 static void
9516  bool *ICContext = nullptr) {
9517  if (E->isTypeDependent() || E->isValueDependent()) return;
9518 
9519  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9520  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9521  if (Source == Target) return;
9522  if (Target->isDependentType()) return;
9523 
9524  // If the conversion context location is invalid don't complain. We also
9525  // don't want to emit a warning if the issue occurs from the expansion of
9526  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9527  // delay this check as long as possible. Once we detect we are in that
9528  // scenario, we just return.
9529  if (CC.isInvalid())
9530  return;
9531 
9532  // Diagnose implicit casts to bool.
9533  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9534  if (isa<StringLiteral>(E))
9535  // Warn on string literal to bool. Checks for string literals in logical
9536  // and expressions, for instance, assert(0 && "error here"), are
9537  // prevented by a check in AnalyzeImplicitConversions().
9538  return DiagnoseImpCast(S, E, T, CC,
9539  diag::warn_impcast_string_literal_to_bool);
9540  if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9541  isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9542  // This covers the literal expressions that evaluate to Objective-C
9543  // objects.
9544  return DiagnoseImpCast(S, E, T, CC,
9545  diag::warn_impcast_objective_c_literal_to_bool);
9546  }
9547  if (Source->isPointerType() || Source->canDecayToPointerType()) {
9548  // Warn on pointer to bool conversion that is always true.
9549  S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9550  SourceRange(CC));
9551  }
9552  }
9553 
9554  // Check implicit casts from Objective-C collection literals to specialized
9555  // collection types, e.g., NSArray<NSString *> *.
9556  if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9557  checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9558  else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9559  checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9560 
9561  // Strip vector types.
9562  if (isa<VectorType>(Source)) {
9563  if (!isa<VectorType>(Target)) {
9564  if (S.SourceMgr.isInSystemMacro(CC))
9565  return;
9566  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9567  }
9568 
9569  // If the vector cast is cast between two vectors of the same size, it is
9570  // a bitcast, not a conversion.
9571  if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9572  return;
9573 
9574  Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9575  Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9576  }
9577  if (auto VecTy = dyn_cast<VectorType>(Target))
9578  Target = VecTy->getElementType().getTypePtr();
9579 
9580  // Strip complex types.
9581  if (isa<ComplexType>(Source)) {
9582  if (!isa<ComplexType>(Target)) {
9583  if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9584  return;
9585 
9586  return DiagnoseImpCast(S, E, T, CC,
9587  S.getLangOpts().CPlusPlus
9588  ? diag::err_impcast_complex_scalar
9589  : diag::warn_impcast_complex_scalar);
9590  }
9591 
9592  Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9593  Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9594  }
9595 
9596  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9597  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9598 
9599  // If the source is floating point...
9600  if (SourceBT && SourceBT->isFloatingPoint()) {
9601  // ...and the target is floating point...
9602  if (TargetBT && TargetBT->isFloatingPoint()) {
9603  // ...then warn if we're dropping FP rank.
9604 
9605  // Builtin FP kinds are ordered by increasing FP rank.
9606  if (SourceBT->getKind() > TargetBT->getKind()) {
9607  // Don't warn about float constants that are precisely
9608  // representable in the target type.
9609  Expr::EvalResult result;
9610  if (E->EvaluateAsRValue(result, S.Context)) {
9611  // Value might be a float, a float vector, or a float complex.
9612  if (IsSameFloatAfterCast(result.Val,
9613  S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9614  S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9615  return;
9616  }
9617 
9618  if (S.SourceMgr.isInSystemMacro(CC))
9619  return;
9620 
9621  DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9622  }
9623  // ... or possibly if we're increasing rank, too
9624  else if (TargetBT->getKind() > SourceBT->getKind()) {
9625  if (S.SourceMgr.isInSystemMacro(CC))
9626  return;
9627 
9628  DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9629  }
9630  return;
9631  }
9632 
9633  // If the target is integral, always warn.
9634  if (TargetBT && TargetBT->isInteger()) {
9635  if (S.SourceMgr.isInSystemMacro(CC))
9636  return;
9637 
9638  DiagnoseFloatingImpCast(S, E, T, CC);
9639  }
9640 
9641  // Detect the case where a call result is converted from floating-point to
9642  // to bool, and the final argument to the call is converted from bool, to
9643  // discover this typo:
9644  //
9645  // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9646  //
9647  // FIXME: This is an incredibly special case; is there some more general
9648  // way to detect this class of misplaced-parentheses bug?
9649  if (Target->isBooleanType() && isa<CallExpr>(E)) {
9650  // Check last argument of function call to see if it is an
9651  // implicit cast from a type matching the type the result
9652  // is being cast to.
9653  CallExpr *CEx = cast<CallExpr>(E);
9654  if (unsigned NumArgs = CEx->getNumArgs()) {
9655  Expr *LastA = CEx->getArg(NumArgs - 1);
9656  Expr *InnerE = LastA->IgnoreParenImpCasts();
9657  if (isa<ImplicitCastExpr>(LastA) &&
9658  InnerE->getType()->isBooleanType()) {
9659  // Warn on this floating-point to bool conversion
9660  DiagnoseImpCast(S, E, T, CC,
9661  diag::warn_impcast_floating_point_to_bool);
9662  }
9663  }
9664  }
9665  return;
9666  }
9667 
9668  DiagnoseNullConversion(S, E, T, CC);
9669 
9670  S.DiscardMisalignedMemberAddress(Target, E);
9671 
9672  if (!Source->isIntegerType() || !Target->isIntegerType())
9673  return;
9674 
9675  // TODO: remove this early return once the false positives for constant->bool
9676  // in templates, macros, etc, are reduced or removed.
9677  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9678  return;
9679 
9680  IntRange SourceRange = GetExprRange(S.Context, E);
9681  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9682 
9683  if (SourceRange.Width > TargetRange.Width) {
9684  // If the source is a constant, use a default-on diagnostic.
9685  // TODO: this should happen for bitfield stores, too.
9686  llvm::APSInt Value(32);
9687  if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9688  if (S.SourceMgr.isInSystemMacro(CC))
9689  return;
9690 
9691  std::string PrettySourceValue = Value.toString(10);
9692  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9693 
9694  S.DiagRuntimeBehavior(E->getExprLoc(), E,
9695  S.PDiag(diag::warn_impcast_integer_precision_constant)
9696  << PrettySourceValue << PrettyTargetValue
9697  << E->getType() << T << E->getSourceRange()
9698  << clang::SourceRange(CC));
9699  return;
9700  }
9701 
9702  // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9703  if (S.SourceMgr.isInSystemMacro(CC))
9704  return;
9705 
9706  if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9707  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9708  /* pruneControlFlow */ true);
9709  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9710  }
9711 
9712  if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9713  SourceRange.NonNegative && Source->isSignedIntegerType()) {
9714  // Warn when doing a signed to signed conversion, warn if the positive
9715  // source value is exactly the width of the target type, which will
9716  // cause a negative value to be stored.
9717 
9718  llvm::APSInt Value;
9719  if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9720  !S.SourceMgr.isInSystemMacro(CC)) {
9721  if (isSameWidthConstantConversion(S, E, T, CC)) {
9722  std::string PrettySourceValue = Value.toString(10);
9723  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9724 
9726  E->getExprLoc(), E,
9727  S.PDiag(diag::warn_impcast_integer_precision_constant)
9728  << PrettySourceValue << PrettyTargetValue << E->getType() << T
9729  << E->getSourceRange() << clang::SourceRange(CC));
9730  return;
9731  }
9732  }
9733 
9734  // Fall through for non-constants to give a sign conversion warning.
9735  }
9736 
9737  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9738  (!TargetRange.NonNegative && SourceRange.NonNegative &&
9739  SourceRange.Width == TargetRange.Width)) {
9740  if (S.SourceMgr.isInSystemMacro(CC))
9741  return;
9742 
9743  unsigned DiagID = diag::warn_impcast_integer_sign;
9744 
9745  // Traditionally, gcc has warned about this under -Wsign-compare.
9746  // We also want to warn about it in -Wconversion.
9747  // So if -Wconversion is off, use a completely identical diagnostic
9748  // in the sign-compare group.
9749  // The conditional-checking code will
9750  if (ICContext) {
9751  DiagID = diag::warn_impcast_integer_sign_conditional;
9752  *ICContext = true;
9753  }
9754 
9755  return DiagnoseImpCast(S, E, T, CC, DiagID);
9756  }
9757 
9758  // Diagnose conversions between different enumeration types.
9759  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9760  // type, to give us better diagnostics.
9761  QualType SourceType = E->getType();
9762  if (!S.getLangOpts().CPlusPlus) {
9763  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9764  if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9765  EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9766  SourceType = S.Context.getTypeDeclType(Enum);
9767  Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9768  }
9769  }
9770 
9771  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9772  if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9773  if (SourceEnum->getDecl()->hasNameForLinkage() &&
9774  TargetEnum->getDecl()->hasNameForLinkage() &&
9775  SourceEnum != TargetEnum) {
9776  if (S.SourceMgr.isInSystemMacro(CC))
9777  return;
9778 
9779  return DiagnoseImpCast(S, E, SourceType, T, CC,
9780  diag::warn_impcast_different_enum_types);
9781  }
9782 }
9783 
9785  SourceLocation CC, QualType T);
9786 
9788  SourceLocation CC, bool &ICContext) {
9789  E = E->IgnoreParenImpCasts();
9790 
9791  if (isa<ConditionalOperator>(E))
9792  return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9793 
9794  AnalyzeImplicitConversions(S, E, CC);
9795  if (E->getType() != T)
9796  return CheckImplicitConversion(S, E, T, CC, &ICContext);
9797 }
9798 
9800  SourceLocation CC, QualType T) {
9802 
9803  bool Suspicious = false;
9804  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9805  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9806 
9807  // If -Wconversion would have warned about either of the candidates
9808  // for a signedness conversion to the context type...
9809  if (!Suspicious) return;
9810 
9811  // ...but it's currently ignored...
9812  if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9813  return;
9814 
9815  // ...then check whether it would have warned about either of the
9816  // candidates for a signedness conversion to the condition type.
9817  if (E->getType() == T) return;
9818 
9819  Suspicious = false;
9821  E->getType(), CC, &Suspicious);
9822  if (!Suspicious)
9824  E->getType(), CC, &Suspicious);
9825 }
9826 
9827 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9828 /// Input argument E is a logical expression.
9830  if (S.getLangOpts().Bool)
9831  return;
9833 }
9834 
9835 /// AnalyzeImplicitConversions - Find and report any interesting
9836 /// implicit conversions in the given expression. There are a couple
9837 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9838 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9839  SourceLocation CC) {
9840  QualType T = OrigE->getType();
9841  Expr *E = OrigE->IgnoreParenImpCasts();
9842 
9843  if (E->isTypeDependent() || E->isValueDependent())
9844  return;
9845 
9846  // For conditional operators, we analyze the arguments as if they
9847  // were being fed directly into the output.
9848  if (isa<ConditionalOperator>(E)) {
9849  ConditionalOperator *CO = cast<ConditionalOperator>(E);
9850  CheckConditionalOperator(S, CO, CC, T);
9851  return;
9852  }
9853 
9854  // Check implicit argument conversions for function calls.
9855  if (CallExpr *Call = dyn_cast<CallExpr>(E))
9856  CheckImplicitArgumentConversions(S, Call, CC);
9857 
9858  // Go ahead and check any implicit conversions we might have skipped.
9859  // The non-canonical typecheck is just an optimization;
9860  // CheckImplicitConversion will filter out dead implicit conversions.
9861  if (E->getType() != T)
9862  CheckImplicitConversion(S, E, T, CC);
9863 
9864  // Now continue drilling into this expression.
9865 
9866  if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9867  // The bound subexpressions in a PseudoObjectExpr are not reachable
9868  // as transitive children.
9869  // FIXME: Use a more uniform representation for this.
9870  for (auto *SE : POE->semantics())
9871  if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9872  AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9873  }
9874 
9875  // Skip past explicit casts.
9876  if (isa<ExplicitCastExpr>(E)) {
9877  E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9878  return AnalyzeImplicitConversions(S, E, CC);
9879  }
9880 
9881  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9882  // Do a somewhat different check with comparison operators.
9883  if (BO->isComparisonOp())
9884  return AnalyzeComparison(S, BO);
9885 
9886  // And with simple assignments.
9887  if (BO->getOpcode() == BO_Assign)
9888  return AnalyzeAssignment(S, BO);
9889  }
9890 
9891  // These break the otherwise-useful invariant below. Fortunately,
9892  // we don't really need to recurse into them, because any internal
9893  // expressions should have been analyzed already when they were
9894  // built into statements.
9895  if (isa<StmtExpr>(E)) return;
9896 
9897  // Don't descend into unevaluated contexts.
9898  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9899 
9900  // Now just recurse over the expression's children.
9901  CC = E->getExprLoc();
9902  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9903  bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9904  for (Stmt *SubStmt : E->children()) {
9905  Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9906  if (!ChildExpr)
9907  continue;
9908 
9909  if (IsLogicalAndOperator &&
9910  isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9911  // Ignore checking string literals that are in logical and operators.
9912  // This is a common pattern for asserts.
9913  continue;
9914  AnalyzeImplicitConversions(S, ChildExpr, CC);
9915  }
9916 
9917  if (BO && BO->isLogicalOp()) {
9918  Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9919  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9920  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9921 
9922  SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9923  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9924  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9925  }
9926 
9927  if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9928  if (U->getOpcode() == UO_LNot)
9929  ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9930 }
9931 
9932 /// Diagnose integer type and any valid implicit convertion to it.
9933 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9934  // Taking into account implicit conversions,
9935  // allow any integer.
9936  if (!E->getType()->isIntegerType()) {
9937  S.Diag(E->getLocStart(),
9938  diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9939  return true;
9940  }
9941  // Potentially emit standard warnings for implicit conversions if enabled
9942  // using -Wconversion.
9943  CheckImplicitConversion(S, E, IntT, E->getLocStart());
9944  return false;
9945 }
9946 
9947 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9948 // Returns true when emitting a warning about taking the address of a reference.
9949 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9950  const PartialDiagnostic &PD) {
9951  E = E->IgnoreParenImpCasts();
9952 
9953  const FunctionDecl *FD = nullptr;
9954 
9955  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9956  if (!DRE->getDecl()->getType()->isReferenceType())
9957  return false;
9958  } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9959  if (!M->getMemberDecl()->getType()->isReferenceType())
9960  return false;
9961  } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9962  if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9963  return false;
9964  FD = Call->getDirectCallee();
9965  } else {
9966  return false;
9967  }
9968 
9969  SemaRef.Diag(E->getExprLoc(), PD);
9970 
9971  // If possible, point to location of function.
9972  if (FD) {
9973  SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9974  }
9975 
9976  return true;
9977 }
9978 
9979 // Returns true if the SourceLocation is expanded from any macro body.
9980 // Returns false if the SourceLocation is invalid, is from not in a macro
9981 // expansion, or is from expanded from a top-level macro argument.
9983  if (Loc.isInvalid())
9984  return false;
9985 
9986  while (Loc.isMacroID()) {
9987  if (SM.isMacroBodyExpansion(Loc))
9988  return true;
9989  Loc = SM.getImmediateMacroCallerLoc(Loc);
9990  }
9991 
9992  return false;
9993 }
9994 
9995 /// \brief Diagnose pointers that are always non-null.
9996 /// \param E the expression containing the pointer
9997 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9998 /// compared to a null pointer
9999 /// \param IsEqual True when the comparison is equal to a null pointer
10000 /// \param Range Extra SourceRange to highlight in the diagnostic
10003  bool IsEqual, SourceRange Range) {
10004  if (!E)
10005  return;
10006 
10007  // Don't warn inside macros.
10008  if (E->getExprLoc().isMacroID()) {
10009  const SourceManager &SM = getSourceManager();
10010  if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10011  IsInAnyMacroBody(SM, Range.getBegin()))
10012  return;
10013  }
10014  E = E->IgnoreImpCasts();
10015 
10016  const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10017 
10018  if (isa<CXXThisExpr>(E)) {
10019  unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10020  : diag::warn_this_bool_conversion;
10021  Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10022  return;
10023  }
10024 
10025  bool IsAddressOf = false;
10026 
10027  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10028  if (UO->getOpcode() != UO_AddrOf)
10029  return;
10030  IsAddressOf = true;
10031  E = UO->getSubExpr();
10032  }
10033 
10034  if (IsAddressOf) {
10035  unsigned DiagID = IsCompare
10036  ? diag::warn_address_of_reference_null_compare
10037  : diag::warn_address_of_reference_bool_conversion;
10038  PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10039  << IsEqual;
10040  if (CheckForReference(*this, E, PD)) {
10041  return;
10042  }
10043  }
10044 
10045  auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10046  bool IsParam = isa<NonNullAttr>(NonnullAttr);
10047  std::string Str;
10048  llvm::raw_string_ostream S(Str);
10049  E->printPretty(S, nullptr, getPrintingPolicy());
10050  unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10051  : diag::warn_cast_nonnull_to_bool;
10052  Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10053  << E->getSourceRange() << Range << IsEqual;
10054  Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10055  };
10056 
10057  // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10058  if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10059  if (auto *Callee = Call->getDirectCallee()) {
10060  if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10061  ComplainAboutNonnullParamOrCall(A);
10062  return;
10063  }
10064  }
10065  }
10066 
10067  // Expect to find a single Decl. Skip anything more complicated.
10068  ValueDecl *D = nullptr;
10069  if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10070  D = R->getDecl();
10071  } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10072  D = M->getMemberDecl();
10073  }
10074 
10075  // Weak Decls can be null.
10076  if (!D || D->isWeak())
10077  return;
10078 
10079  // Check for parameter decl with nonnull attribute
10080  if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10081  if (getCurFunction() &&
10082  !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10083  if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10084  ComplainAboutNonnullParamOrCall(A);
10085  return;
10086  }
10087 
10088  if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10089  auto ParamIter = llvm::find(FD->parameters(), PV);
10090  assert(ParamIter != FD->param_end());
10091  unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10092 
10093  for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10094  if (!NonNull->args_size()) {
10095  ComplainAboutNonnullParamOrCall(NonNull);
10096  return;
10097  }
10098 
10099  for (unsigned ArgNo : NonNull->args()) {
10100  if (ArgNo == ParamNo) {
10101  ComplainAboutNonnullParamOrCall(NonNull);
10102  return;
10103  }
10104  }
10105  }
10106  }
10107  }
10108  }
10109 
10110  QualType T = D->getType();
10111  const bool IsArray = T->isArrayType();
10112  const bool IsFunction = T->isFunctionType();
10113 
10114  // Address of function is used to silence the function warning.
10115  if (IsAddressOf && IsFunction) {
10116  return;
10117  }
10118 
10119  // Found nothing.
10120  if (!IsAddressOf && !IsFunction && !IsArray)
10121  return;
10122 
10123  // Pretty print the expression for the diagnostic.
10124  std::string Str;
10125  llvm::raw_string_ostream S(Str);
10126  E->printPretty(S, nullptr, getPrintingPolicy());
10127 
10128  unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10129  : diag::warn_impcast_pointer_to_bool;
10130  enum {
10131  AddressOf,
10132  FunctionPointer,
10133  ArrayPointer
10134  } DiagType;
10135  if (IsAddressOf)
10136  DiagType = AddressOf;
10137  else if (IsFunction)
10138  DiagType = FunctionPointer;
10139  else if (IsArray)
10140  DiagType = ArrayPointer;
10141  else
10142  llvm_unreachable("Could not determine diagnostic.");
10143  Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10144  << Range << IsEqual;
10145 
10146  if (!IsFunction)
10147  return;
10148 
10149  // Suggest '&' to silence the function warning.
10150  Diag(E->getExprLoc(), diag::note_function_warning_silence)
10152 
10153  // Check to see if '()' fixit should be emitted.
10154  QualType ReturnType;
10155  UnresolvedSet<4> NonTemplateOverloads;
10156  tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10157  if (ReturnType.isNull())
10158  return;
10159 
10160  if (IsCompare) {
10161  // There are two cases here. If there is null constant, the only suggest
10162  // for a pointer return type. If the null is 0, then suggest if the return
10163  // type is a pointer or an integer type.
10164  if (!ReturnType->isPointerType()) {
10165  if (NullKind == Expr::NPCK_ZeroExpression ||
10166  NullKind == Expr::NPCK_ZeroLiteral) {
10167  if (!ReturnType->isIntegerType())
10168  return;
10169  } else {
10170  return;
10171  }
10172  }
10173  } else { // !IsCompare
10174  // For function to bool, only suggest if the function pointer has bool
10175  // return type.
10176  if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10177  return;
10178  }
10179  Diag(E->getExprLoc(), diag::note_function_to_function_call)
10180  << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10181 }
10182 
10183 /// Diagnoses "dangerous" implicit conversions within the given
10184 /// expression (which is a full expression). Implements -Wconversion
10185 /// and -Wsign-compare.
10186 ///
10187 /// \param CC the "context" location of the implicit conversion, i.e.
10188 /// the most location of the syntactic entity requiring the implicit
10189 /// conversion
10190 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10191  // Don't diagnose in unevaluated contexts.
10192  if (isUnevaluatedContext())
10193  return;
10194 
10195  // Don't diagnose for value- or type-dependent expressions.
10196  if (E->isTypeDependent() || E->isValueDependent())
10197  return;
10198 
10199  // Check for array bounds violations in cases where the check isn't triggered
10200  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10201  // ArraySubscriptExpr is on the RHS of a variable initialization.
10202  CheckArrayAccess(E);
10203 
10204  // This is not the right CC for (e.g.) a variable initialization.
10205  AnalyzeImplicitConversions(*this, E, CC);
10206 }
10207 
10208 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10209 /// Input argument E is a logical expression.
10210 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10211  ::CheckBoolLikeConversion(*this, E, CC);
10212 }
10213 
10214 /// Diagnose when expression is an integer constant expression and its evaluation
10215 /// results in integer overflow
10216 void Sema::CheckForIntOverflow (Expr *E) {
10217  // Use a work list to deal with nested struct initializers.
10218  SmallVector<Expr *, 2> Exprs(1, E);
10219 
10220  do {
10221  Expr *E = Exprs.pop_back_val();
10222 
10223  if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10224  E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10225  continue;
10226  }
10227 
10228  if (auto InitList = dyn_cast<InitListExpr>(E))
10229  Exprs.append(InitList->inits().begin(), InitList->inits().end());
10230 
10231  if (isa<ObjCBoxedExpr>(E))
10232  E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10233  } while (!Exprs.empty());
10234 }
10235 
10236 namespace {
10237 
10238 /// \brief Visitor for expressions which looks for unsequenced operations on the
10239 /// same object.
10240 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10242 
10243  /// \brief A tree of sequenced regions within an expression. Two regions are
10244  /// unsequenced if one is an ancestor or a descendent of the other. When we
10245  /// finish processing an expression with sequencing, such as a comma
10246  /// expression, we fold its tree nodes into its parent, since they are
10247  /// unsequenced with respect to nodes we will visit later.
10248  class SequenceTree {
10249  struct Value {
10250  explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10251  unsigned Parent : 31;
10252  unsigned Merged : 1;
10253  };
10254  SmallVector<Value, 8> Values;
10255 
10256  public:
10257  /// \brief A region within an expression which may be sequenced with respect
10258  /// to some other region.
10259  class Seq {
10260  friend class SequenceTree;
10261 
10262  unsigned Index = 0;
10263 
10264  explicit Seq(unsigned N) : Index(N) {}
10265 
10266  public:
10267  Seq() = default;
10268  };
10269 
10270  SequenceTree() { Values.push_back(Value(0)); }
10271  Seq root() const { return Seq(0); }
10272 
10273  /// \brief Create a new sequence of operations, which is an unsequenced
10274  /// subset of \p Parent. This sequence of operations is sequenced with
10275  /// respect to other children of \p Parent.
10276  Seq allocate(Seq Parent) {
10277  Values.push_back(Value(Parent.Index));
10278  return Seq(Values.size() - 1);
10279  }
10280 
10281  /// \brief Merge a sequence of operations into its parent.
10282  void merge(Seq S) {
10283  Values[S.Index].Merged = true;
10284  }
10285 
10286  /// \brief Determine whether two operations are unsequenced. This operation
10287  /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10288  /// should have been merged into its parent as appropriate.
10289  bool isUnsequenced(Seq Cur, Seq Old) {
10290  unsigned C = representative(Cur.Index);
10291  unsigned Target = representative(Old.Index);
10292  while (C >= Target) {
10293  if (C == Target)
10294  return true;
10295  C = Values[C].Parent;
10296  }
10297  return false;
10298  }
10299 
10300  private:
10301  /// \brief Pick a representative for a sequence.
10302  unsigned representative(unsigned K) {
10303  if (Values[K].Merged)
10304  // Perform path compression as we go.
10305  return Values[K].Parent = representative(Values[K].Parent);
10306  return K;
10307  }
10308  };
10309 
10310  /// An object for which we can track unsequenced uses.
10311  using Object = NamedDecl *;
10312 
10313  /// Different flavors of object usage which we track. We only track the
10314  /// least-sequenced usage of each kind.
10315  enum UsageKind {
10316  /// A read of an object. Multiple unsequenced reads are OK.
10317  UK_Use,
10318 
10319  /// A modification of an object which is sequenced before the value
10320  /// computation of the expression, such as ++n in C++.
10321  UK_ModAsValue,
10322 
10323  /// A modification of an object which is not sequenced before the value
10324  /// computation of the expression, such as n++.
10325  UK_ModAsSideEffect,
10326 
10327  UK_Count = UK_ModAsSideEffect + 1
10328  };
10329 
10330  struct Usage {
10331  Expr *Use = nullptr;
10332  SequenceTree::Seq Seq;
10333 
10334  Usage() = default;
10335  };
10336 
10337  struct UsageInfo {
10338  Usage Uses[UK_Count];
10339 
10340  /// Have we issued a diagnostic for this variable already?
10341  bool Diagnosed = false;
10342 
10343  UsageInfo() = default;
10344  };
10345  using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10346 
10347  Sema &SemaRef;
10348 
10349  /// Sequenced regions within the expression.
10350  SequenceTree Tree;
10351 
10352  /// Declaration modifications and references which we have seen.
10353  UsageInfoMap UsageMap;
10354 
10355  /// The region we are currently within.
10356  SequenceTree::Seq Region;
10357 
10358  /// Filled in with declarations which were modified as a side-effect
10359  /// (that is, post-increment operations).
10360  SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10361 
10362  /// Expressions to check later. We defer checking these to reduce
10363  /// stack usage.
10364  SmallVectorImpl<Expr *> &WorkList;
10365 
10366  /// RAII object wrapping the visitation of a sequenced subexpression of an
10367  /// expression. At the end of this process, the side-effects of the evaluation
10368  /// become sequenced with respect to the value computation of the result, so
10369  /// we downgrade any UK_ModAsSideEffect within the evaluation to
10370  /// UK_ModAsValue.
10371  struct SequencedSubexpression {
10372  SequencedSubexpression(SequenceChecker &Self)
10373  : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10374  Self.ModAsSideEffect = &ModAsSideEffect;
10375  }
10376 
10377  ~SequencedSubexpression() {
10378  for (auto &M : llvm::reverse(ModAsSideEffect)) {
10379  UsageInfo &U = Self.UsageMap[M.first];
10380  auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10381  Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10382  SideEffectUsage = M.second;
10383  }
10384  Self.ModAsSideEffect = OldModAsSideEffect;
10385  }
10386 
10387  SequenceChecker &Self;
10388  SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10389  SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
10390  };
10391 
10392  /// RAII object wrapping the visitation of a subexpression which we might
10393  /// choose to evaluate as a constant. If any subexpression is evaluated and
10394  /// found to be non-constant, this allows us to suppress the evaluation of
10395  /// the outer expression.
10396  class EvaluationTracker {
10397  public:
10398  EvaluationTracker(SequenceChecker &Self)
10399  : Self(Self), Prev(Self.EvalTracker) {
10400  Self.EvalTracker = this;
10401  }
10402 
10403  ~EvaluationTracker() {
10404  Self.EvalTracker = Prev;
10405  if (Prev)
10406  Prev->EvalOK &= EvalOK;
10407  }
10408 
10409  bool evaluate(const Expr *E, bool &Result) {
10410  if (!EvalOK || E->isValueDependent())
10411  return false;
10412  EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10413  return EvalOK;
10414  }
10415 
10416  private:
10417  SequenceChecker &Self;
10418  EvaluationTracker *Prev;
10419  bool EvalOK = true;
10420  } *EvalTracker = nullptr;
10421 
10422  /// \brief Find the object which is produced by the specified expression,
10423  /// if any.
10424  Object getObject(Expr *E, bool Mod) const {
10425  E = E->IgnoreParenCasts();
10426  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10427  if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10428  return getObject(UO->getSubExpr(), Mod);
10429  } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10430  if (BO->getOpcode() == BO_Comma)
10431  return getObject(BO->getRHS(), Mod);
10432  if (Mod && BO->isAssignmentOp())
10433  return getObject(BO->getLHS(), Mod);
10434  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10435  // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10436  if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10437  return ME->getMemberDecl();
10438  } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10439  // FIXME: If this is a reference, map through to its value.
10440  return DRE->getDecl();
10441  return nullptr;
10442  }
10443 
10444  /// \brief Note that an object was modified or used by an expression.
10445  void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10446  Usage &U = UI.Uses[UK];
10447  if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10448  if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10449  ModAsSideEffect->push_back(std::make_pair(O, U));
10450  U.Use = Ref;
10451  U.Seq = Region;
10452  }
10453  }
10454 
10455  /// \brief Check whether a modification or use conflicts with a prior usage.
10456  void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10457  bool IsModMod) {
10458  if (UI.Diagnosed)
10459  return;
10460 
10461  const Usage &U = UI.Uses[OtherKind];
10462  if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10463  return;
10464 
10465  Expr *Mod = U.Use;
10466  Expr *ModOrUse = Ref;
10467  if (OtherKind == UK_Use)
10468  std::swap(Mod, ModOrUse);
10469 
10470  SemaRef.Diag(Mod->getExprLoc(),
10471  IsModMod ? diag::warn_unsequenced_mod_mod
10472  : diag::warn_unsequenced_mod_use)
10473  << O << SourceRange(ModOrUse->getExprLoc());
10474  UI.Diagnosed = true;
10475  }
10476 
10477  void notePreUse(Object O, Expr *Use) {
10478  UsageInfo &U = UsageMap[O];
10479  // Uses conflict with other modifications.
10480  checkUsage(O, U, Use, UK_ModAsValue, false);
10481  }
10482 
10483  void notePostUse(Object O, Expr *Use) {
10484  UsageInfo &U = UsageMap[O];
10485  checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10486  addUsage(U, O, Use, UK_Use);
10487  }
10488 
10489  void notePreMod(Object O, Expr *Mod) {
10490  UsageInfo &U = UsageMap[O];
10491  // Modifications conflict with other modifications and with uses.
10492  checkUsage(O, U, Mod, UK_ModAsValue, true);
10493  checkUsage(O, U, Mod, UK_Use, false);
10494  }
10495 
10496  void notePostMod(Object O, Expr *Use, UsageKind UK) {
10497  UsageInfo &U = UsageMap[O];
10498  checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10499  addUsage(U, O, Use, UK);
10500  }
10501 
10502 public:
10503  SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10504  : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10505  Visit(E);
10506  }
10507 
10508  void VisitStmt(Stmt *S) {
10509  // Skip all statements which aren't expressions for now.
10510  }
10511 
10512  void VisitExpr(Expr *E) {
10513  // By default, just recurse to evaluated subexpressions.
10514  Base::VisitStmt(E);
10515  }
10516 
10517  void VisitCastExpr(CastExpr *E) {
10518  Object O = Object();
10519  if (E->getCastKind() == CK_LValueToRValue)
10520  O = getObject(E->getSubExpr(), false);
10521 
10522  if (O)
10523  notePreUse(O, E);
10524  VisitExpr(E);
10525  if (O)
10526  notePostUse(O, E);
10527  }
10528 
10529  void VisitBinComma(BinaryOperator *BO) {
10530  // C++11 [expr.comma]p1:
10531  // Every value computation and side effect associated with the left
10532  // expression is sequenced before every value computation and side
10533  // effect associated with the right expression.
10534  SequenceTree::Seq LHS = Tree.allocate(Region);
10535  SequenceTree::Seq RHS = Tree.allocate(Region);
10536  SequenceTree::Seq OldRegion = Region;
10537 
10538  {
10539  SequencedSubexpression SeqLHS(*this);
10540  Region = LHS;
10541  Visit(BO->getLHS());
10542  }
10543 
10544  Region = RHS;
10545  Visit(BO->getRHS());
10546 
10547  Region = OldRegion;
10548 
10549  // Forget that LHS and RHS are sequenced. They are both unsequenced
10550  // with respect to other stuff.
10551  Tree.merge(LHS);
10552  Tree.merge(RHS);
10553  }
10554 
10555  void VisitBinAssign(BinaryOperator *BO) {
10556  // The modification is sequenced after the value computation of the LHS
10557  // and RHS, so check it before inspecting the operands and update the
10558  // map afterwards.
10559  Object O = getObject(BO->getLHS(), true);
10560  if (!O)
10561  return VisitExpr(BO);
10562 
10563  notePreMod(O, BO);
10564 
10565  // C++11 [expr.ass]p7:
10566  // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10567  // only once.
10568  //
10569  // Therefore, for a compound assignment operator, O is considered used
10570  // everywhere except within the evaluation of E1 itself.
10571  if (isa<CompoundAssignOperator>(BO))
10572  notePreUse(O, BO);
10573 
10574  Visit(BO->getLHS());
10575 
10576  if (isa<CompoundAssignOperator>(BO))
10577  notePostUse(O, BO);
10578 
10579  Visit(BO->getRHS());
10580 
10581  // C++11 [expr.ass]p1:
10582  // the assignment is sequenced [...] before the value computation of the
10583  // assignment expression.
10584  // C11 6.5.16/3 has no such rule.
10585  notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10586  : UK_ModAsSideEffect);
10587  }
10588 
10589  void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10590  VisitBinAssign(CAO);
10591  }
10592 
10593  void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10594  void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10595  void VisitUnaryPreIncDec(UnaryOperator *UO) {
10596  Object O = getObject(UO->getSubExpr(), true);
10597  if (!O)
10598  return VisitExpr(UO);
10599 
10600  notePreMod(O, UO);
10601  Visit(UO->getSubExpr());
10602  // C++11 [expr.pre.incr]p1:
10603  // the expression ++x is equivalent to x+=1
10604  notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10605  : UK_ModAsSideEffect);
10606  }
10607 
10608  void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10609  void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10610  void VisitUnaryPostIncDec(UnaryOperator *UO) {
10611  Object O = getObject(UO->getSubExpr(), true);
10612  if (!O)
10613  return VisitExpr(UO);
10614 
10615  notePreMod(O, UO);
10616  Visit(UO->getSubExpr());
10617  notePostMod(O, UO, UK_ModAsSideEffect);
10618  }
10619 
10620  /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10621  void VisitBinLOr(BinaryOperator *BO) {
10622  // The side-effects of the LHS of an '&&' are sequenced before the
10623  // value computation of the RHS, and hence before the value computation
10624  // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10625  // as if they were unconditionally sequenced.
10626  EvaluationTracker Eval(*this);
10627  {
10628  SequencedSubexpression Sequenced(*this);
10629  Visit(BO->getLHS());
10630  }
10631 
10632  bool Result;
10633  if (Eval.evaluate(BO->getLHS(), Result)) {
10634  if (!Result)
10635  Visit(BO->getRHS());
10636  } else {
10637  // Check for unsequenced operations in the RHS, treating it as an
10638  // entirely separate evaluation.
10639  //
10640  // FIXME: If there are operations in the RHS which are unsequenced
10641  // with respect to operations outside the RHS, and those operations
10642  // are unconditionally evaluated, diagnose them.
10643  WorkList.push_back(BO->getRHS());
10644  }
10645  }
10646  void VisitBinLAnd(BinaryOperator *BO) {
10647  EvaluationTracker Eval(*this);
10648  {
10649  SequencedSubexpression Sequenced(*this);
10650  Visit(BO->getLHS());
10651  }
10652 
10653  bool Result;
10654  if (Eval.evaluate(BO->getLHS(), Result)) {
10655  if (Result)
10656  Visit(BO->getRHS());
10657  } else {
10658  WorkList.push_back(BO->getRHS());
10659  }
10660  }
10661 
10662  // Only visit the condition, unless we can be sure which subexpression will
10663  // be chosen.
10664  void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10665  EvaluationTracker Eval(*this);
10666  {
10667  SequencedSubexpression Sequenced(*this);
10668  Visit(CO->getCond());
10669  }
10670 
10671  bool Result;
10672  if (Eval.evaluate(CO->getCond(), Result))
10673  Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10674  else {
10675  WorkList.push_back(CO->getTrueExpr());
10676  WorkList.push_back(CO->getFalseExpr());
10677  }
10678  }
10679 
10680  void VisitCallExpr(CallExpr *CE) {
10681  // C++11 [intro.execution]p15:
10682  // When calling a function [...], every value computation and side effect
10683  // associated with any argument expression, or with the postfix expression
10684  // designating the called function, is sequenced before execution of every
10685  // expression or statement in the body of the function [and thus before
10686  // the value computation of its result].
10687  SequencedSubexpression Sequenced(*this);
10688  Base::VisitCallExpr(CE);
10689 
10690  // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10691  }
10692 
10693  void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10694  // This is a call, so all subexpressions are sequenced before the result.
10695  SequencedSubexpression Sequenced(*this);
10696 
10697  if (!CCE->isListInitialization())
10698  return VisitExpr(CCE);
10699 
10700  // In C++11, list initializations are sequenced.
10702  SequenceTree::Seq Parent = Region;
10703  for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10704  E = CCE->arg_end();
10705  I != E; ++I) {
10706  Region = Tree.allocate(Parent);
10707  Elts.push_back(Region);
10708  Visit(*I);
10709  }
10710 
10711  // Forget that the initializers are sequenced.
10712  Region = Parent;
10713  for (unsigned I = 0; I < Elts.size(); ++I)
10714  Tree.merge(Elts[I]);
10715  }
10716 
10717  void VisitInitListExpr(InitListExpr *ILE) {
10718  if (!SemaRef.getLangOpts().CPlusPlus11)
10719  return VisitExpr(ILE);
10720 
10721  // In C++11, list initializations are sequenced.
10723  SequenceTree::Seq Parent = Region;
10724  for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10725  Expr *E = ILE->getInit(I);
10726  if (!E) continue;
10727  Region = Tree.allocate(Parent);
10728  Elts.push_back(Region);
10729  Visit(E);
10730  }
10731 
10732  // Forget that the initializers are sequenced.
10733  Region = Parent;
10734  for (unsigned I = 0; I < Elts.size(); ++I)
10735  Tree.merge(Elts[I]);
10736  }
10737 };
10738 
10739 } // namespace
10740 
10741 void Sema::CheckUnsequencedOperations(Expr *E) {
10742  SmallVector<Expr *, 8> WorkList;
10743  WorkList.push_back(E);
10744  while (!WorkList.empty()) {
10745  Expr *Item = WorkList.pop_back_val();
10746  SequenceChecker(*this, Item, WorkList);
10747  }
10748 }
10749 
10750 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10751  bool IsConstexpr) {
10752  CheckImplicitConversions(E, CheckLoc);
10753  if (!E->isInstantiationDependent())
10754  CheckUnsequencedOperations(E);
10755  if (!IsConstexpr && !E->isValueDependent())
10756  CheckForIntOverflow(E);
10757  DiagnoseMisalignedMembers();
10758 }
10759 
10760 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10761  FieldDecl *BitField,
10762  Expr *Init) {
10763  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10764 }
10765 
10767  SourceLocation Loc) {
10768  if (!PType->isVariablyModifiedType())
10769  return;
10770  if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10771  diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10772  return;
10773  }
10774  if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10775  diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10776  return;
10777  }
10778  if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10779  diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10780  return;
10781  }
10782 
10783  const ArrayType *AT = S.Context.getAsArrayType(PType);
10784  if (!AT)
10785  return;
10786 
10787  if (AT->getSizeModifier() != ArrayType::Star) {
10789  return;
10790  }
10791 
10792  S.Diag(Loc, diag::err_array_star_in_function_definition);
10793 }
10794 
10795 /// CheckParmsForFunctionDef - Check that the parameters of the given
10796 /// function are appropriate for the definition of a function. This
10797 /// takes care of any checks that cannot be performed on the
10798 /// declaration itself, e.g., that the types of each of the function
10799 /// parameters are complete.
10801  bool CheckParameterNames) {
10802  bool HasInvalidParm = false;
10803  for (ParmVarDecl *Param : Parameters) {
10804  // C99 6.7.5.3p4: the parameters in a parameter type list in a
10805  // function declarator that is part of a function definition of
10806  // that function shall not have incomplete type.
10807  //
10808  // This is also C++ [dcl.fct]p6.
10809  if (!Param->isInvalidDecl() &&
10810  RequireCompleteType(Param->getLocation(), Param->getType(),
10811  diag::err_typecheck_decl_incomplete_type)) {
10812  Param->setInvalidDecl();
10813  HasInvalidParm = true;
10814  }
10815 
10816  // C99 6.9.1p5: If the declarator includes a parameter type list, the
10817  // declaration of each parameter shall include an identifier.
10818  if (CheckParameterNames &&
10819  Param->getIdentifier() == nullptr &&
10820  !Param->isImplicit() &&
10821  !getLangOpts().CPlusPlus)
10822  Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10823 
10824  // C99 6.7.5.3p12:
10825  // If the function declarator is not part of a definition of that
10826  // function, parameters may have incomplete type and may use the [*]
10827  // notation in their sequences of declarator specifiers to specify
10828  // variable length array types.
10829  QualType PType = Param->getOriginalType();
10830  // FIXME: This diagnostic should point the '[*]' if source-location
10831  // information is added for it.
10832  diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10833 
10834  // MSVC destroys objects passed by value in the callee. Therefore a
10835  // function definition which takes such a parameter must be able to call the
10836  // object's destructor. However, we don't perform any direct access check
10837  // on the dtor.
10838  if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10839  .getCXXABI()
10841  if (!Param->isInvalidDecl()) {
10842  if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10843  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10844  if (!ClassDecl->isInvalidDecl() &&
10845  !ClassDecl->hasIrrelevantDestructor() &&
10846  !ClassDecl->isDependentContext()) {
10847  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10848  MarkFunctionReferenced(Param->getLocation(), Destructor);
10849  DiagnoseUseOfDecl(Destructor, Param->getLocation());
10850  }
10851  }
10852  }
10853  }
10854 
10855  // Parameters with the pass_object_size attribute only need to be marked
10856  // constant at function definitions. Because we lack information about
10857  // whether we're on a declaration or definition when we're instantiating the
10858  // attribute, we need to check for constness here.
10859  if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10860  if (!Param->getType().isConstQualified())
10861  Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10862  << Attr->getSpelling() << 1;
10863  }
10864 
10865  return HasInvalidParm;
10866 }
10867 
10868 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10869 /// or MemberExpr.
10870 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10871  ASTContext &Context) {
10872  if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10873  return Context.getDeclAlign(DRE->getDecl());
10874 
10875  if (const auto *ME = dyn_cast<MemberExpr>(E))
10876  return Context.getDeclAlign(ME->getMemberDecl());
10877 
10878  return TypeAlign;
10879 }
10880 
10881 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10882 /// pointer cast increases the alignment requirements.
10884  // This is actually a lot of work to potentially be doing on every
10885  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10886  if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10887  return;
10888 
10889  // Ignore dependent types.
10890  if (T->isDependentType() || Op->getType()->isDependentType())
10891  return;
10892 
10893  // Require that the destination be a pointer type.
10894  const PointerType *DestPtr = T->getAs<PointerType>();
10895  if (!DestPtr) return;
10896 
10897  // If the destination has alignment 1, we're done.
10898  QualType DestPointee = DestPtr->getPointeeType();
10899  if (DestPointee->isIncompleteType()) return;
10900  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10901  if (DestAlign.isOne()) return;
10902 
10903  // Require that the source be a pointer type.
10904  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10905  if (!SrcPtr) return;
10906  QualType SrcPointee = SrcPtr->getPointeeType();
10907 
10908  // Whitelist casts from cv void*. We already implicitly
10909  // whitelisted casts to cv void*, since they have alignment 1.
10910  // Also whitelist casts involving incomplete types, which implicitly
10911  // includes 'void'.
10912  if (SrcPointee->isIncompleteType()) return;
10913 
10914  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10915 
10916  if (auto *CE = dyn_cast<CastExpr>(Op)) {
10917  if (CE->getCastKind() == CK_ArrayToPointerDecay)
10918  SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10919  } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10920  if (UO->getOpcode() == UO_AddrOf)
10921  SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10922  }
10923 
10924  if (SrcAlign >= DestAlign) return;
10925 
10926  Diag(TRange.getBegin(), diag::warn_cast_align)
10927  << Op->getType() << T
10928  << static_cast<unsigned>(SrcAlign.getQuantity())
10929  << static_cast<unsigned>(DestAlign.getQuantity())
10930  << TRange << Op->getSourceRange();
10931 }
10932 
10933 /// \brief Check whether this array fits the idiom of a size-one tail padded
10934 /// array member of a struct.
10935 ///
10936 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10937 /// commonly used to emulate flexible arrays in C89 code.
10938 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10939  const NamedDecl *ND) {
10940  if (Size != 1 || !ND) return false;
10941 
10942  const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10943  if (!FD) return false;
10944 
10945  // Don't consider sizes resulting from macro expansions or template argument
10946  // substitution to form C89 tail-padded arrays.
10947 
10948  TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10949  while (TInfo) {
10950  TypeLoc TL = TInfo->getTypeLoc();
10951  // Look through typedefs.
10952  if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10953  const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10954  TInfo = TDL->getTypeSourceInfo();
10955  continue;
10956  }
10958  const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10959  if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10960  return false;
10961  }
10962  break;
10963  }
10964 
10965  const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10966  if (!RD) return false;
10967  if (RD->isUnion()) return false;
10968  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10969  if (!CRD->isStandardLayout()) return false;
10970  }
10971 
10972  // See if this is the last field decl in the record.
10973  const Decl *D = FD;
10974  while ((D = D->getNextDeclInContext()))
10975  if (isa<FieldDecl>(D))
10976  return false;
10977  return true;
10978 }
10979 
10980 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10981  const ArraySubscriptExpr *ASE,
10982  bool AllowOnePastEnd, bool IndexNegated) {
10983  IndexExpr = IndexExpr->IgnoreParenImpCasts();
10984  if (IndexExpr->isValueDependent())
10985  return;
10986 
10987  const Type *EffectiveType =
10988  BaseExpr->getType()->getPointeeOrArrayElementType();
10989  BaseExpr = BaseExpr->IgnoreParenCasts();
10990  const ConstantArrayType *ArrayTy =
10991  Context.getAsConstantArrayType(BaseExpr->getType());
10992  if (!ArrayTy)
10993  return;
10994 
10995  llvm::APSInt index;
10996  if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10997  return;
10998  if (IndexNegated)
10999  index = -index;
11000 
11001  const NamedDecl *ND = nullptr;
11002  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11003  ND = dyn_cast<NamedDecl>(DRE->getDecl());
11004  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11005  ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11006 
11007  if (index.isUnsigned() || !index.isNegative()) {
11008  llvm::APInt size = ArrayTy->getSize();
11009  if (!size.isStrictlyPositive())
11010  return;
11011 
11012  const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11013  if (BaseType != EffectiveType) {
11014  // Make sure we're comparing apples to apples when comparing index to size
11015  uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11016  uint64_t array_typesize = Context.getTypeSize(BaseType);
11017  // Handle ptrarith_typesize being zero, such as when casting to void*
11018  if (!ptrarith_typesize) ptrarith_typesize = 1;
11019  if (ptrarith_typesize != array_typesize) {
11020  // There's a cast to a different size type involved
11021  uint64_t ratio = array_typesize / ptrarith_typesize;
11022  // TODO: Be smarter about handling cases where array_typesize is not a
11023  // multiple of ptrarith_typesize
11024  if (ptrarith_typesize * ratio == array_typesize)
11025  size *= llvm::APInt(size.getBitWidth(), ratio);
11026  }
11027  }
11028 
11029  if (size.getBitWidth() > index.getBitWidth())
11030  index = index.zext(size.getBitWidth());
11031  else if (size.getBitWidth() < index.getBitWidth())
11032  size = size.zext(index.getBitWidth());
11033 
11034  // For array subscripting the index must be less than size, but for pointer
11035  // arithmetic also allow the index (offset) to be equal to size since
11036  // computing the next address after the end of the array is legal and
11037  // commonly done e.g. in C++ iterators and range-based for loops.
11038  if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11039  return;
11040 
11041  // Also don't warn for arrays of size 1 which are members of some
11042  // structure. These are often used to approximate flexible arrays in C89
11043  // code.
11044  if (IsTailPaddedMemberArray(*this, size, ND))
11045  return;
11046 
11047  // Suppress the warning if the subscript expression (as identified by the
11048  // ']' location) and the index expression are both from macro expansions
11049  // within a system header.
11050  if (ASE) {
11051  SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11052  ASE->getRBracketLoc());
11053  if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11054  SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11055  IndexExpr->getLocStart());
11056  if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11057  return;
11058  }
11059  }
11060 
11061  unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11062  if (ASE)
11063  DiagID = diag::warn_array_index_exceeds_bounds;
11064 
11065  DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11066  PDiag(DiagID) << index.toString(10, true)
11067  << size.toString(10, true)
11068  << (unsigned)size.getLimitedValue(~0U)
11069  << IndexExpr->getSourceRange());
11070  } else {
11071  unsigned DiagID = diag::warn_array_index_precedes_bounds;
11072  if (!ASE) {
11073  DiagID = diag::warn_ptr_arith_precedes_bounds;
11074  if (index.isNegative()) index = -index;
11075  }
11076 
11077  DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11078  PDiag(DiagID) << index.toString(10, true)
11079  << IndexExpr->getSourceRange());
11080  }
11081 
11082  if (!ND) {
11083  // Try harder to find a NamedDecl to point at in the note.
11084  while (const ArraySubscriptExpr *ASE =
11085  dyn_cast<ArraySubscriptExpr>(BaseExpr))
11086  BaseExpr = ASE->getBase()->IgnoreParenCasts();
11087  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11088  ND = dyn_cast<NamedDecl>(DRE->getDecl());
11089  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11090  ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11091  }
11092 
11093  if (ND)
11094  DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11095  PDiag(diag::note_array_index_out_of_bounds)
11096  << ND->getDeclName());
11097 }
11098 
11099 void Sema::CheckArrayAccess(const Expr *expr) {
11100  int AllowOnePastEnd = 0;
11101  while (expr) {
11102  expr = expr->IgnoreParenImpCasts();
11103  switch (expr->getStmtClass()) {
11104  case Stmt::ArraySubscriptExprClass: {
11105  const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11106  CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11107  AllowOnePastEnd > 0);
11108  return;
11109  }
11110  case Stmt::OMPArraySectionExprClass: {
11111  const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11112  if (ASE->getLowerBound())
11113  CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11114  /*ASE=*/nullptr, AllowOnePastEnd > 0);
11115  return;
11116  }
11117  case Stmt::UnaryOperatorClass: {
11118  // Only unwrap the * and & unary operators
11119  const UnaryOperator *UO = cast<UnaryOperator>(expr);
11120  expr = UO->getSubExpr();
11121  switch (UO->getOpcode()) {
11122  case UO_AddrOf:
11123  AllowOnePastEnd++;
11124  break;
11125  case UO_Deref:
11126  AllowOnePastEnd--;
11127  break;
11128  default:
11129  return;
11130  }
11131  break;
11132  }
11133  case Stmt::ConditionalOperatorClass: {
11134  const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11135  if (const Expr *lhs = cond->getLHS())
11136  CheckArrayAccess(lhs);
11137  if (const Expr *rhs = cond->getRHS())
11138  CheckArrayAccess(rhs);
11139  return;
11140  }
11141  case Stmt::CXXOperatorCallExprClass: {
11142  const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11143  for (const auto *Arg : OCE->arguments())
11144  CheckArrayAccess(Arg);
11145  return;
11146  }
11147  default:
11148  return;
11149  }
11150  }
11151 }
11152 
11153 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11154 
11155 namespace {
11156 
11157 struct RetainCycleOwner {
11158  VarDecl *Variable = nullptr;
11159  SourceRange Range;
11160  SourceLocation Loc;
11161  bool Indirect = false;
11162 
11163  RetainCycleOwner() = default;
11164 
11165  void setLocsFrom(Expr *e) {
11166  Loc = e->getExprLoc();
11167  Range = e->getSourceRange();
11168  }
11169 };
11170 
11171 } // namespace
11172 
11173 /// Consider whether capturing the given variable can possibly lead to
11174 /// a retain cycle.
11175 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11176  // In ARC, it's captured strongly iff the variable has __strong
11177  // lifetime. In MRR, it's captured strongly if the variable is
11178  // __block and has an appropriate type.
11180  return false;
11181 
11182  owner.Variable = var;
11183  if (ref)
11184  owner.setLocsFrom(ref);
11185  return true;
11186 }
11187 
11188 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11189  while (true) {
11190  e = e->IgnoreParens();
11191  if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11192  switch (cast->getCastKind()) {
11193  case CK_BitCast:
11194  case CK_LValueBitCast:
11195  case CK_LValueToRValue:
11196  case CK_ARCReclaimReturnedObject:
11197  e = cast->getSubExpr();
11198  continue;
11199 
11200  default:
11201  return false;
11202  }
11203  }
11204 
11205  if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11206  ObjCIvarDecl *ivar = ref->getDecl();
11208  return false;
11209 
11210  // Try to find a retain cycle in the base.
11211  if (!findRetainCycleOwner(S, ref->getBase(), owner))
11212  return false;
11213 
11214  if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11215  owner.Indirect = true;
11216  return true;
11217  }
11218 
11219  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11220  VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11221  if (!var) return false;
11222  return considerVariable(var, ref, owner);
11223  }
11224 
11225  if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11226  if (member->isArrow()) return false;
11227 
11228  // Don't count this as an indirect ownership.
11229  e = member->getBase();
11230  continue;
11231  }
11232 
11233  if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11234  // Only pay attention to pseudo-objects on property references.
11235  ObjCPropertyRefExpr *pre
11236  = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11237  ->IgnoreParens());
11238  if (!pre) return false;
11239  if (pre->isImplicitProperty()) return false;
11240  ObjCPropertyDecl *property = pre->getExplicitProperty();
11241  if (!property->isRetaining() &&
11242  !(property->getPropertyIvarDecl() &&
11243  property->getPropertyIvarDecl()->getType()
11244  .getObjCLifetime() == Qualifiers::OCL_Strong))
11245  return false;
11246 
11247  owner.Indirect = true;
11248  if (pre->isSuperReceiver()) {
11249  owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11250  if (!owner.Variable)
11251  return false;
11252  owner.Loc = pre->getLocation();
11253  owner.Range = pre->getSourceRange();
11254  return true;
11255  }
11256  e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11257  ->getSourceExpr());
11258  continue;
11259  }
11260 
11261  // Array ivars?
11262 
11263  return false;
11264  }
11265 }
11266 
11267 namespace {
11268 
11269  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11270  ASTContext &Context;
11271  VarDecl *Variable;
11272  Expr *Capturer = nullptr;
11273  bool VarWillBeReased = false;
11274 
11275  FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11277  Context(Context), Variable(variable) {}
11278 
11279  void VisitDeclRefExpr(DeclRefExpr *ref) {
11280  if (ref->getDecl() == Variable && !Capturer)
11281  Capturer = ref;
11282  }
11283 
11284  void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11285  if (Capturer) return;
11286  Visit(ref->getBase());
11287  if (Capturer && ref->isFreeIvar())
11288  Capturer = ref;
11289  }
11290 
11291  void VisitBlockExpr(BlockExpr *block) {
11292  // Look inside nested blocks
11293  if (block->getBlockDecl()->capturesVariable(Variable))
11294  Visit(block->getBlockDecl()->getBody());
11295  }
11296 
11297  void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11298  if (Capturer) return;
11299  if (OVE->getSourceExpr())
11300  Visit(OVE->getSourceExpr());
11301  }
11302 
11303  void VisitBinaryOperator(BinaryOperator *BinOp) {
11304  if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11305  return;
11306  Expr *LHS = BinOp->getLHS();
11307  if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11308  if (DRE->getDecl() != Variable)
11309  return;
11310  if (Expr *RHS = BinOp->getRHS()) {
11311  RHS = RHS->IgnoreParenCasts();
11312  llvm::APSInt Value;
11313  VarWillBeReased =
11314  (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11315  }
11316  }
11317  }
11318  };
11319 
11320 } // namespace
11321 
11322 /// Check whether the given argument is a block which captures a
11323 /// variable.
11324 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11325  assert(owner.Variable && owner.Loc.isValid());
11326 
11327  e = e->IgnoreParenCasts();
11328 
11329  // Look through [^{...} copy] and Block_copy(^{...}).
11330  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11331  Selector Cmd = ME->getSelector();
11332  if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11333  e = ME->getInstanceReceiver();
11334  if (!e)
11335  return nullptr;
11336  e = e->IgnoreParenCasts();
11337  }
11338  } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11339  if (CE->getNumArgs() == 1) {
11340  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11341  if (Fn) {
11342  const IdentifierInfo *FnI = Fn->getIdentifier();
11343  if (FnI && FnI->isStr("_Block_copy")) {
11344  e = CE->getArg(0)->IgnoreParenCasts();
11345  }
11346  }
11347  }
11348  }
11349 
11350  BlockExpr *block = dyn_cast<BlockExpr>(e);
11351  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11352  return nullptr;
11353 
11354  FindCaptureVisitor visitor(S.Context, owner.Variable);
11355  visitor.Visit(block->getBlockDecl()->getBody());
11356  return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11357 }
11358 
11359 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11360  RetainCycleOwner &owner) {
11361  assert(capturer);
11362  assert(owner.Variable && owner.Loc.isValid());
11363 
11364  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11365  << owner.Variable << capturer->getSourceRange();
11366  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11367  << owner.Indirect << owner.Range;
11368 }
11369 
11370 /// Check for a keyword selector that starts with the word 'add' or
11371 /// 'set'.
11372 static bool isSetterLikeSelector(Selector sel) {
11373  if (sel.isUnarySelector()) return false;
11374 
11375  StringRef str = sel.getNameForSlot(0);
11376  while (!str.empty() && str.front() == '_') str = str.substr(1);
11377  if (str.startswith("set"))
11378  str = str.substr(3);
11379  else if (str.startswith("add")) {
11380  // Specially whitelist 'addOperationWithBlock:'.
11381  if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11382  return false;
11383  str = str.substr(3);
11384  }
11385  else
11386  return false;
11387 
11388  if (str.empty()) return true;
11389  return !isLowercase(str.front());
11390 }
11391 
11393  ObjCMessageExpr *Message) {
11394  bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11395  Message->getReceiverInterface(),
11397  if (!IsMutableArray) {
11398  return None;
11399  }
11400 
11401  Selector Sel = Message->getSelector();
11402 
11404  S.NSAPIObj->getNSArrayMethodKind(Sel);
11405  if (!MKOpt) {
11406  return None;
11407  }
11408 
11409  NSAPI::NSArrayMethodKind MK = *MKOpt;
11410 
11411  switch (MK) {
11415  return 0;
11417  return 1;
11418 
11419  default:
11420  return None;
11421  }
11422 
11423  return None;
11424 }
11425 
11426 static
11428  ObjCMessageExpr *Message) {
11429  bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11430  Message->getReceiverInterface(),
11432  if (!IsMutableDictionary) {
11433  return None;
11434  }
11435 
11436  Selector Sel = Message->getSelector();
11437 
11439  S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11440  if (!MKOpt) {
11441  return None;
11442  }
11443 
11444  NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11445 
11446  switch (MK) {
11450  return 0;
11451 
11452  default:
11453  return None;
11454  }
11455 
11456  return None;
11457 }
11458 
11460  bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11461  Message->getReceiverInterface(),
11463 
11464  bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11465  Message->getReceiverInterface(),
11467  if (!IsMutableSet && !IsMutableOrderedSet) {
11468  return None;
11469  }
11470 
11471  Selector Sel = Message->getSelector();
11472 
11473  Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11474  if (!MKOpt) {
11475  return None;
11476  }
11477 
11478  NSAPI::NSSetMethodKind MK = *MKOpt;
11479 
11480  switch (MK) {
11485  return 0;
11487  return 1;
11488  }
11489 
11490  return None;
11491 }
11492 
11493 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11494  if (!Message->isInstanceMessage()) {
11495  return;
11496  }
11497 
11498  Optional<int> ArgOpt;
11499 
11500  if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11501  !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11502  !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11503  return;
11504  }
11505 
11506  int ArgIndex = *ArgOpt;
11507 
11508  Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11509  if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11510  Arg = OE->getSourceExpr()->IgnoreImpCasts();
11511  }
11512 
11513  if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11514  if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11515  if (ArgRE->isObjCSelfExpr()) {
11516  Diag(Message->getSourceRange().getBegin(),
11517  diag::warn_objc_circular_container)
11518  << ArgRE->getDecl()->getName() << StringRef("super");
11519  }
11520  }
11521  } else {
11522  Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11523 
11524  if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11525  Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11526  }
11527 
11528  if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11529  if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11530  if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11531  ValueDecl *Decl = ReceiverRE->getDecl();
11532  Diag(Message->getSourceRange().getBegin(),
11533  diag::warn_objc_circular_container)
11534  << Decl->getName() << Decl->getName();
11535  if (!ArgRE->isObjCSelfExpr()) {
11536  Diag(Decl->getLocation(),
11537  diag::note_objc_circular_container_declared_here)
11538  << Decl->getName();
11539  }
11540  }
11541  }
11542  } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11543  if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11544  if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11545  ObjCIvarDecl *Decl = IvarRE->getDecl();
11546  Diag(Message->getSourceRange().getBegin(),
11547  diag::warn_objc_circular_container)
11548  << Decl->getName() << Decl->getName();
11549  Diag(Decl->getLocation(),
11550  diag::note_objc_circular_container_declared_here)
11551  << Decl->getName();
11552  }
11553  }
11554  }
11555  }
11556 }
11557 
11558 /// Check a message send to see if it's likely to cause a retain cycle.
11560  // Only check instance methods whose selector looks like a setter.
11561  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11562  return;
11563 
11564  // Try to find a variable that the receiver is strongly owned by.
11565  RetainCycleOwner owner;
11567  if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11568  return;
11569  } else {
11571  owner.Variable = getCurMethodDecl()->getSelfDecl();
11572  owner.Loc = msg->getSuperLoc();
11573  owner.Range = msg->getSuperLoc();
11574  }
11575 
11576  // Check whether the receiver is captured by any of the arguments.
11577  const ObjCMethodDecl *MD = msg->getMethodDecl();
11578  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11579  if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11580  // noescape blocks should not be retained by the method.
11581  if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11582  continue;
11583  return diagnoseRetainCycle(*this, capturer, owner);
11584  }
11585  }
11586 }
11587 
11588 /// Check a property assign to see if it's likely to cause a retain cycle.
11589 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11590  RetainCycleOwner owner;
11591  if (!findRetainCycleOwner(*this, receiver, owner))
11592  return;
11593 
11594  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11595  diagnoseRetainCycle(*this, capturer, owner);
11596 }
11597 
11599  RetainCycleOwner Owner;
11600  if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11601  return;
11602 
11603  // Because we don't have an expression for the variable, we have to set the
11604  // location explicitly here.
11605  Owner.Loc = Var->getLocation();
11606  Owner.Range = Var->getSourceRange();
11607 
11608  if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11609  diagnoseRetainCycle(*this, Capturer, Owner);
11610 }
11611 
11613  Expr *RHS, bool isProperty) {
11614  // Check if RHS is an Objective-C object literal, which also can get
11615  // immediately zapped in a weak reference. Note that we explicitly
11616  // allow ObjCStringLiterals, since those are designed to never really die.
11617  RHS = RHS->IgnoreParenImpCasts();
11618 
11619  // This enum needs to match with the 'select' in
11620  // warn_objc_arc_literal_assign (off-by-1).
11622  if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11623  return false;
11624 
11625  S.Diag(Loc, diag::warn_arc_literal_assign)
11626  << (unsigned) Kind
11627  << (isProperty ? 0 : 1)
11628  << RHS->getSourceRange();
11629 
11630  return true;
11631 }
11632 
11635  Expr *RHS, bool isProperty) {
11636  // Strip off any implicit cast added to get to the one ARC-specific.
11637  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11638  if (cast->getCastKind() == CK_ARCConsumeObject) {
11639  S.Diag(Loc, diag::warn_arc_retained_assign)
11640  << (LT == Qualifiers::OCL_ExplicitNone)
11641  << (isProperty ? 0 : 1)
11642  << RHS->getSourceRange();
11643  return true;
11644  }
11645  RHS = cast->getSubExpr();
11646  }
11647 
11648  if (LT == Qualifiers::OCL_Weak &&
11649  checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11650  return true;
11651 
11652  return false;
11653 }
11654 
11656  QualType LHS, Expr *RHS) {
11658 
11660  return false;
11661 
11662  if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11663  return true;
11664 
11665  return false;
11666 }
11667 
11669  Expr *LHS, Expr *RHS) {
11670  QualType LHSType;
11671  // PropertyRef on LHS type need be directly obtained from
11672  // its declaration as it has a PseudoType.
11673  ObjCPropertyRefExpr *PRE
11674  = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11675  if (PRE && !PRE->isImplicitProperty()) {
11676  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11677  if (PD)
11678  LHSType = PD->getType();
11679  }
11680 
11681  if (LHSType.isNull())
11682  LHSType = LHS->getType();
11683 
11685 
11686  if (LT == Qualifiers::OCL_Weak) {
11687  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11688  getCurFunction()->markSafeWeakUse(LHS);
11689  }
11690 
11691  if (checkUnsafeAssigns(Loc, LHSType, RHS))
11692  return;
11693 
11694  // FIXME. Check for other life times.
11695  if (LT != Qualifiers::OCL_None)
11696  return;
11697 
11698  if (PRE) {
11699  if (PRE->isImplicitProperty())
11700  return;
11701  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11702  if (!PD)
11703  return;
11704 
11705  unsigned Attributes = PD->getPropertyAttributes();
11706  if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11707  // when 'assign' attribute was not explicitly specified
11708  // by user, ignore it and rely on property type itself
11709  // for lifetime info.
11710  unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11711  if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11712  LHSType->isObjCRetainableType())
11713  return;
11714 
11715  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11716  if (cast->getCastKind() == CK_ARCConsumeObject) {
11717  Diag(Loc, diag::warn_arc_retained_property_assign)
11718  << RHS->getSourceRange();
11719  return;
11720  }
11721  RHS = cast->getSubExpr();
11722  }
11723  }
11724  else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11725  if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11726  return;
11727  }
11728  }
11729 }
11730 
11731 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11732 
11733 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11734  SourceLocation StmtLoc,
11735  const NullStmt *Body) {
11736  // Do not warn if the body is a macro that expands to nothing, e.g:
11737  //
11738  // #define CALL(x)
11739  // if (condition)
11740  // CALL(0);
11741  if (Body->hasLeadingEmptyMacro())
11742  return false;
11743 
11744  // Get line numbers of statement and body.
11745  bool StmtLineInvalid;
11746  unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11747  &StmtLineInvalid);
11748  if (StmtLineInvalid)
11749  return false;
11750 
11751  bool BodyLineInvalid;
11752  unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11753  &BodyLineInvalid);
11754  if (BodyLineInvalid)
11755  return false;
11756 
11757  // Warn if null statement and body are on the same line.
11758  if (StmtLine != BodyLine)
11759  return false;
11760 
11761  return true;
11762 }
11763 
11765  const Stmt *Body,
11766  unsigned DiagID) {
11767  // Since this is a syntactic check, don't emit diagnostic for template
11768  // instantiations, this just adds noise.
11769  if (CurrentInstantiationScope)
11770  return;
11771 
11772  // The body should be a null statement.
11773  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11774  if (!NBody)
11775  return;
11776 
11777  // Do the usual checks.
11778  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11779  return;
11780 
11781  Diag(NBody->getSemiLoc(), DiagID);
11782  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11783 }
11784 
11786  const Stmt *PossibleBody) {
11787  assert(!CurrentInstantiationScope); // Ensured by caller
11788 
11789  SourceLocation StmtLoc;
11790  const Stmt *Body;
11791  unsigned DiagID;
11792  if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11793  StmtLoc = FS->getRParenLoc();
11794  Body = FS->getBody();
11795  DiagID = diag::warn_empty_for_body;
11796  } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11797  StmtLoc = WS->getCond()->getSourceRange().getEnd();
11798  Body = WS->getBody();
11799  DiagID = diag::warn_empty_while_body;
11800  } else
11801  return; // Neither `for' nor `while'.
11802 
11803  // The body should be a null statement.
11804  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11805  if (!NBody)
11806  return;
11807 
11808  // Skip expensive checks if diagnostic is disabled.
11809  if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11810  return;
11811 
11812  // Do the usual checks.
11813  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11814  return;
11815 
11816  // `for(...);' and `while(...);' are popular idioms, so in order to keep
11817  // noise level low, emit diagnostics only if for/while is followed by a
11818  // CompoundStmt, e.g.:
11819  // for (int i = 0; i < n; i++);
11820  // {
11821  // a(i);
11822  // }
11823  // or if for/while is followed by a statement with more indentation
11824  // than for/while itself:
11825  // for (int i = 0; i < n; i++);
11826  // a(i);
11827  bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11828  if (!ProbableTypo) {
11829  bool BodyColInvalid;
11830  unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11831  PossibleBody->getLocStart(),
11832  &BodyColInvalid);
11833  if (BodyColInvalid)
11834  return;
11835 
11836  bool StmtColInvalid;
11837  unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11838  S->getLocStart(),
11839  &StmtColInvalid);
11840  if (StmtColInvalid)
11841  return;
11842 
11843  if (BodyCol > StmtCol)
11844  ProbableTypo = true;
11845  }
11846 
11847  if (ProbableTypo) {
11848  Diag(NBody->getSemiLoc(), DiagID);
11849  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11850  }
11851 }
11852 
11853 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11854 
11855 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11856 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11857  SourceLocation OpLoc) {
11858  if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11859  return;
11860 
11861  if (inTemplateInstantiation())
11862  return;
11863 
11864  // Strip parens and casts away.
11865  LHSExpr = LHSExpr->IgnoreParenImpCasts();
11866  RHSExpr = RHSExpr->IgnoreParenImpCasts();
11867 
11868  // Check for a call expression
11869  const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11870  if (!CE || CE->getNumArgs() != 1)
11871  return;
11872 
11873  // Check for a call to std::move
11874  if (!CE->isCallToStdMove())
11875  return;
11876 
11877  // Get argument from std::move
11878  RHSExpr = CE->getArg(0);
11879 
11880  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11881  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11882 
11883  // Two DeclRefExpr's, check that the decls are the same.
11884  if (LHSDeclRef && RHSDeclRef) {
11885  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11886  return;
11887  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11888  RHSDeclRef->getDecl()->getCanonicalDecl())
11889  return;
11890 
11891  Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11892  << LHSExpr->getSourceRange()
11893  << RHSExpr->getSourceRange();
11894  return;
11895  }
11896 
11897  // Member variables require a different approach to check for self moves.
11898  // MemberExpr's are the same if every nested MemberExpr refers to the same
11899  // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11900  // the base Expr's are CXXThisExpr's.
11901  const Expr *LHSBase = LHSExpr;
11902  const Expr *RHSBase = RHSExpr;
11903  const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11904  const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11905  if (!LHSME || !RHSME)
11906  return;
11907 
11908  while (LHSME && RHSME) {
11909  if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11910  RHSME->getMemberDecl()->getCanonicalDecl())
11911  return;
11912 
11913  LHSBase = LHSME->getBase();
11914  RHSBase = RHSME->getBase();
11915  LHSME = dyn_cast<MemberExpr>(LHSBase);
11916  RHSME = dyn_cast<MemberExpr>(RHSBase);
11917  }
11918 
11919  LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11920  RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11921  if (LHSDeclRef && RHSDeclRef) {
11922  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11923  return;
11924  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11925  RHSDeclRef->getDecl()->getCanonicalDecl())
11926  return;
11927 
11928  Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11929  << LHSExpr->getSourceRange()
11930  << RHSExpr->getSourceRange();
11931  return;
11932  }
11933 
11934  if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11935  Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11936  << LHSExpr->getSourceRange()
11937  << RHSExpr->getSourceRange();
11938 }
11939 
11940 //===--- Layout compatibility ----------------------------------------------//
11941 
11942 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11943 
11944 /// \brief Check if two enumeration types are layout-compatible.
11945 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11946  // C++11 [dcl.enum] p8:
11947  // Two enumeration types are layout-compatible if they have the same
11948  // underlying type.
11949  return ED1->isComplete() && ED2->isComplete() &&
11950  C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11951 }
11952 
11953 /// \brief Check if two fields are layout-compatible.
11954 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
11955  FieldDecl *Field2) {
11956  if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11957  return false;
11958 
11959  if (Field1->isBitField() != Field2->isBitField())
11960  return false;
11961 
11962  if (Field1->isBitField()) {
11963  // Make sure that the bit-fields are the same length.
11964  unsigned Bits1 = Field1->getBitWidthValue(C);
11965  unsigned Bits2 = Field2->getBitWidthValue(C);
11966 
11967  if (Bits1 != Bits2)
11968  return false;
11969  }
11970 
11971  return true;
11972 }
11973 
11974 /// \brief Check if two standard-layout structs are layout-compatible.
11975 /// (C++11 [class.mem] p17)
11977  RecordDecl *RD2) {
11978  // If both records are C++ classes, check that base classes match.
11979  if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11980  // If one of records is a CXXRecordDecl we are in C++ mode,
11981  // thus the other one is a CXXRecordDecl, too.
11982  const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11983  // Check number of base classes.
11984  if (D1CXX->getNumBases() != D2CXX->getNumBases())
11985  return false;
11986 
11987  // Check the base classes.
11989  Base1 = D1CXX->bases_begin(),
11990  BaseEnd1 = D1CXX->bases_end(),
11991  Base2 = D2CXX->bases_begin();
11992  Base1 != BaseEnd1;
11993  ++Base1, ++Base2) {
11994  if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11995  return false;
11996  }
11997  } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11998  // If only RD2 is a C++ class, it should have zero base classes.
11999  if (D2CXX->getNumBases() > 0)
12000  return false;
12001  }
12002 
12003  // Check the fields.
12004  RecordDecl::field_iterator Field2 = RD2->field_begin(),
12005  Field2End = RD2->field_end(),
12006  Field1 = RD1->field_begin(),
12007  Field1End = RD1->field_end();
12008  for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12009  if (!isLayoutCompatible(C, *Field1, *Field2))
12010  return false;
12011  }
12012  if (Field1 != Field1End || Field2 != Field2End)
12013  return false;
12014 
12015  return true;
12016 }
12017 
12018 /// \brief Check if two standard-layout unions are layout-compatible.
12019 /// (C++11 [class.mem] p18)
12021  RecordDecl *RD2) {
12022  llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12023  for (auto *Field2 : RD2->fields())
12024  UnmatchedFields.insert(Field2);
12025 
12026  for (auto *Field1 : RD1->fields()) {
12027  llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12028  I = UnmatchedFields.begin(),
12029  E = UnmatchedFields.end();
12030 
12031  for ( ; I != E; ++I) {
12032  if (isLayoutCompatible(C, Field1, *I)) {
12033  bool Result = UnmatchedFields.erase(*I);
12034  (void) Result;
12035  assert(Result);
12036  break;
12037  }
12038  }
12039  if (I == E)
12040  return false;
12041  }
12042 
12043  return UnmatchedFields.empty();
12044 }
12045 
12047  RecordDecl *RD2) {
12048  if (RD1->isUnion() != RD2->isUnion())
12049  return false;
12050 
12051  if (RD1->isUnion())
12052  return isLayoutCompatibleUnion(C, RD1, RD2);
12053  else
12054  return isLayoutCompatibleStruct(C, RD1, RD2);
12055 }
12056 
12057 /// \brief Check if two types are layout-compatible in C++11 sense.
12059  if (T1.isNull() || T2.isNull())
12060  return false;
12061 
12062  // C++11 [basic.types] p11:
12063  // If two types T1 and T2 are the same type, then T1 and T2 are
12064  // layout-compatible types.
12065  if (C.hasSameType(T1, T2))
12066  return true;
12067 
12070 
12071  const Type::TypeClass TC1 = T1->getTypeClass();
12072  const Type::TypeClass TC2 = T2->getTypeClass();
12073 
12074  if (TC1 != TC2)
12075  return false;
12076 
12077  if (TC1 == Type::Enum) {
12078  return isLayoutCompatible(C,
12079  cast<EnumType>(T1)->getDecl(),
12080  cast<EnumType>(T2)->getDecl());
12081  } else if (TC1 == Type::Record) {
12082  if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12083  return false;
12084 
12085  return isLayoutCompatible(C,
12086  cast<RecordType>(T1)->getDecl(),
12087  cast<RecordType>(T2)->getDecl());
12088  }
12089 
12090  return false;
12091 }
12092 
12093 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12094 
12095 /// \brief Given a type tag expression find the type tag itself.
12096 ///
12097 /// \param TypeExpr Type tag expression, as it appears in user's code.
12098 ///
12099 /// \param VD Declaration of an identifier that appears in a type tag.
12100 ///
12101 /// \param MagicValue Type tag magic value.
12102 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12103  const ValueDecl **VD, uint64_t *MagicValue) {
12104  while(true) {
12105  if (!TypeExpr)
12106  return false;
12107 
12108  TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12109 
12110  switch (TypeExpr->getStmtClass()) {
12111  case Stmt::UnaryOperatorClass: {
12112  const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12113  if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12114  TypeExpr = UO->getSubExpr();
12115  continue;
12116  }
12117  return false;
12118  }
12119 
12120  case Stmt::DeclRefExprClass: {
12121  const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12122  *VD = DRE->getDecl();
12123  return true;
12124  }
12125 
12126  case Stmt::IntegerLiteralClass: {
12127  const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12128  llvm::APInt MagicValueAPInt = IL->getValue();
12129  if (MagicValueAPInt.getActiveBits() <= 64) {
12130  *MagicValue = MagicValueAPInt.getZExtValue();
12131  return true;
12132  } else
12133  return false;
12134  }
12135 
12136  case Stmt::BinaryConditionalOperatorClass:
12137  case Stmt::ConditionalOperatorClass: {
12138  const AbstractConditionalOperator *ACO =
12139  cast<AbstractConditionalOperator>(TypeExpr);
12140  bool Result;
12141  if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12142  if (Result)
12143  TypeExpr = ACO->getTrueExpr();
12144  else
12145  TypeExpr = ACO->getFalseExpr();
12146  continue;
12147  }
12148  return false;
12149  }
12150 
12151  case Stmt::BinaryOperatorClass: {
12152  const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12153  if (BO->getOpcode() == BO_Comma) {
12154  TypeExpr = BO->getRHS();
12155  continue;
12156  }
12157  return false;
12158  }
12159 
12160  default:
12161  return false;
12162  }
12163  }
12164 }
12165 
12166 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12167 ///
12168 /// \param TypeExpr Expression that specifies a type tag.
12169 ///
12170 /// \param MagicValues Registered magic values.
12171 ///
12172 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12173 /// kind.
12174 ///
12175 /// \param TypeInfo Information about the corresponding C type.
12176 ///
12177 /// \returns true if the corresponding C type was found.
12178 static bool GetMatchingCType(
12179  const IdentifierInfo *ArgumentKind,
12180  const Expr *TypeExpr, const ASTContext &Ctx,
12181  const llvm::DenseMap<Sema::TypeTagMagicValue,
12182  Sema::TypeTagData> *MagicValues,
12183  bool &FoundWrongKind,
12185  FoundWrongKind = false;
12186 
12187  // Variable declaration that has type_tag_for_datatype attribute.
12188  const ValueDecl *VD = nullptr;
12189 
12190  uint64_t MagicValue;
12191 
12192  if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12193  return false;
12194 
12195  if (VD) {
12196  if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12197  if (I->getArgumentKind() != ArgumentKind) {
12198  FoundWrongKind = true;
12199  return false;
12200  }
12201  TypeInfo.Type = I->getMatchingCType();
12202  TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12203  TypeInfo.MustBeNull = I->getMustBeNull();
12204  return true;
12205  }
12206  return false;
12207  }
12208 
12209  if (!MagicValues)
12210  return false;
12211 
12212  llvm::DenseMap<Sema::TypeTagMagicValue,
12213  Sema::TypeTagData>::const_iterator I =
12214  MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12215  if (I == MagicValues->end())
12216  return false;
12217 
12218  TypeInfo = I->second;
12219  return true;
12220 }
12221 
12223  uint64_t MagicValue, QualType Type,
12224  bool LayoutCompatible,
12225  bool MustBeNull) {
12226  if (!TypeTagForDatatypeMagicValues)
12227  TypeTagForDatatypeMagicValues.reset(
12228  new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12229 
12230  TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12231  (*TypeTagForDatatypeMagicValues)[Magic] =
12232  TypeTagData(Type, LayoutCompatible, MustBeNull);
12233 }
12234 
12235 static bool IsSameCharType(QualType T1, QualType T2) {
12236  const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12237  if (!BT1)
12238  return false;
12239 
12240  const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12241  if (!BT2)
12242  return false;
12243 
12244  BuiltinType::Kind T1Kind = BT1->getKind();
12245  BuiltinType::Kind T2Kind = BT2->getKind();
12246 
12247  return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12248  (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12249  (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12250  (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12251 }
12252 
12253 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12254  const ArrayRef<const Expr *> ExprArgs,
12255  SourceLocation CallSiteLoc) {
12256  const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12257  bool IsPointerAttr = Attr->getIsPointer();
12258 
12259  // Retrieve the argument representing the 'type_tag'.
12260  if (Attr->getTypeTagIdx() >= ExprArgs.size()) {
12261  // Add 1 to display the user's specified value.
12262  Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12263  << 0 << Attr->getTypeTagIdx() + 1;
12264  return;
12265  }
12266  const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12267  bool FoundWrongKind;
12268  TypeTagData TypeInfo;
12269  if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12270  TypeTagForDatatypeMagicValues.get(),
12271  FoundWrongKind, TypeInfo)) {
12272  if (FoundWrongKind)
12273  Diag(TypeTagExpr->getExprLoc(),
12274  diag::warn_type_tag_for_datatype_wrong_kind)
12275  << TypeTagExpr->getSourceRange();
12276  return;
12277  }
12278 
12279  // Retrieve the argument representing the 'arg_idx'.
12280  if (Attr->getArgumentIdx() >= ExprArgs.size()) {
12281  // Add 1 to display the user's specified value.
12282  Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12283  << 1 << Attr->getArgumentIdx() + 1;
12284  return;
12285  }
12286  const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12287  if (IsPointerAttr) {
12288  // Skip implicit cast of pointer to `void *' (as a function argument).
12289  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12290  if (ICE->getType()->isVoidPointerType() &&
12291  ICE->getCastKind() == CK_BitCast)
12292  ArgumentExpr = ICE->getSubExpr();
12293  }
12294  QualType ArgumentType = ArgumentExpr->getType();
12295 
12296  // Passing a `void*' pointer shouldn't trigger a warning.
12297  if (IsPointerAttr && ArgumentType->isVoidPointerType())
12298  return;
12299 
12300  if (TypeInfo.MustBeNull) {
12301  // Type tag with matching void type requires a null pointer.
12302  if (!ArgumentExpr->isNullPointerConstant(Context,
12304  Diag(ArgumentExpr->getExprLoc(),
12305  diag::warn_type_safety_null_pointer_required)
12306  << ArgumentKind->getName()
12307  << ArgumentExpr->getSourceRange()
12308  << TypeTagExpr->getSourceRange();
12309  }
12310  return;
12311  }
12312 
12313  QualType RequiredType = TypeInfo.Type;
12314  if (IsPointerAttr)
12315  RequiredType = Context.getPointerType(RequiredType);
12316 
12317  bool mismatch = false;
12318  if (!TypeInfo.LayoutCompatible) {
12319  mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12320 
12321  // C++11 [basic.fundamental] p1:
12322  // Plain char, signed char, and unsigned char are three distinct types.
12323  //
12324  // But we treat plain `char' as equivalent to `signed char' or `unsigned
12325  // char' depending on the current char signedness mode.
12326  if (mismatch)
12327  if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12328  RequiredType->getPointeeType())) ||
12329  (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12330  mismatch = false;
12331  } else
12332  if (IsPointerAttr)
12333  mismatch = !isLayoutCompatible(Context,
12334  ArgumentType->getPointeeType(),
12335  RequiredType->getPointeeType());
12336  else
12337  mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12338 
12339  if (mismatch)
12340  Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12341  << ArgumentType << ArgumentKind
12342  << TypeInfo.LayoutCompatible << RequiredType
12343  << ArgumentExpr->getSourceRange()
12344  << TypeTagExpr->getSourceRange();
12345 }
12346 
12347 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12348  CharUnits Alignment) {
12349  MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12350 }
12351 
12353  for (MisalignedMember &m : MisalignedMembers) {
12354  const NamedDecl *ND = m.RD;
12355  if (ND->getName().empty()) {
12356  if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12357  ND = TD;
12358  }
12359  Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12360  << m.MD << ND << m.E->getSourceRange();
12361  }
12362  MisalignedMembers.clear();
12363 }
12364 
12366  E = E->IgnoreParens();
12367  if (!T->isPointerType() && !T->isIntegerType())
12368  return;
12369  if (isa<UnaryOperator>(E) &&
12370  cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12371  auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12372  if (isa<MemberExpr>(Op)) {
12373  auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12374  MisalignedMember(Op));
12375  if (MA != MisalignedMembers.end() &&
12376  (T->isIntegerType() ||
12377  (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12378  Context.getTypeAlignInChars(
12379  T->getPointeeType()) <= MA->Alignment))))
12380  MisalignedMembers.erase(MA);
12381  }
12382  }
12383 }
12384 
12386  Expr *E,
12387  llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12388  Action) {
12389  const auto *ME = dyn_cast<MemberExpr>(E);
12390  if (!ME)
12391  return;
12392 
12393  // No need to check expressions with an __unaligned-qualified type.
12394  if (E->getType().getQualifiers().hasUnaligned())
12395  return;
12396 
12397  // For a chain of MemberExpr like "a.b.c.d" this list
12398  // will keep FieldDecl's like [d, c, b].
12399  SmallVector<FieldDecl *, 4> ReverseMemberChain;
12400  const MemberExpr *TopME = nullptr;
12401  bool AnyIsPacked = false;
12402  do {
12403  QualType BaseType = ME->getBase()->getType();
12404  if (ME->isArrow())
12405  BaseType = BaseType->getPointeeType();
12406  RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12407  if (RD->isInvalidDecl())
12408  return;
12409 
12410  ValueDecl *MD = ME->getMemberDecl();
12411  auto *FD = dyn_cast<FieldDecl>(MD);
12412  // We do not care about non-data members.
12413  if (!FD || FD->isInvalidDecl())
12414  return;
12415 
12416  AnyIsPacked =
12417  AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12418  ReverseMemberChain.push_back(FD);
12419 
12420  TopME = ME;
12421  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12422  } while (ME);
12423  assert(TopME && "We did not compute a topmost MemberExpr!");
12424 
12425  // Not the scope of this diagnostic.
12426  if (!AnyIsPacked)
12427  return;
12428 
12429  const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12430  const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12431  // TODO: The innermost base of the member expression may be too complicated.
12432  // For now, just disregard these cases. This is left for future
12433  // improvement.
12434  if (!DRE && !isa<CXXThisExpr>(TopBase))
12435  return;
12436 
12437  // Alignment expected by the whole expression.
12438  CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12439 
12440  // No need to do anything else with this case.
12441  if (ExpectedAlignment.isOne())
12442  return;
12443 
12444  // Synthesize offset of the whole access.
12445  CharUnits Offset;
12446  for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12447  I++) {
12448  Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12449  }
12450 
12451  // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12452  CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12453  ReverseMemberChain.back()->getParent()->getTypeForDecl());
12454 
12455  // The base expression of the innermost MemberExpr may give
12456  // stronger guarantees than the class containing the member.
12457  if (DRE && !TopME->isArrow()) {
12458  const ValueDecl *VD = DRE->getDecl();
12459  if (!VD->getType()->isReferenceType())
12460  CompleteObjectAlignment =
12461  std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12462  }
12463 
12464  // Check if the synthesized offset fulfills the alignment.
12465  if (Offset % ExpectedAlignment != 0 ||
12466  // It may fulfill the offset it but the effective alignment may still be
12467  // lower than the expected expression alignment.
12468  CompleteObjectAlignment < ExpectedAlignment) {
12469  // If this happens, we want to determine a sensible culprit of this.
12470  // Intuitively, watching the chain of member expressions from right to
12471  // left, we start with the required alignment (as required by the field
12472  // type) but some packed attribute in that chain has reduced the alignment.
12473  // It may happen that another packed structure increases it again. But if
12474  // we are here such increase has not been enough. So pointing the first
12475  // FieldDecl that either is packed or else its RecordDecl is,
12476  // seems reasonable.
12477  FieldDecl *FD = nullptr;
12478  CharUnits Alignment;
12479  for (FieldDecl *FDI : ReverseMemberChain) {
12480  if (FDI->hasAttr<PackedAttr>() ||
12481  FDI->getParent()->hasAttr<PackedAttr>()) {
12482  FD = FDI;
12483  Alignment = std::min(
12484  Context.getTypeAlignInChars(FD->getType()),
12485  Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12486  break;
12487  }
12488  }
12489  assert(FD && "We did not find a packed FieldDecl!");
12490  Action(E, FD->getParent(), FD, Alignment);
12491  }
12492 }
12493 
12494 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12495  using namespace std::placeholders;
12496 
12497  RefersToMemberWithReducedAlignment(
12498  rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12499  _2, _3, _4));
12500 }
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have...
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:577
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:1060
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static FormatStringType GetFormatStringType(const FormatAttr *Format)
bool isFloatingPoint() const
Definition: Type.h:2189
Defines the clang::ASTContext interface.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
const BlockDecl * getBlockDecl() const
Definition: Expr.h:4865
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:180
VariadicCallType
Definition: Sema.h:9293
bool isCallToStdMove() const
Definition: Expr.h:2351
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
IntType getInt64Type() const
Definition: TargetInfo.h:262
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name...
Definition: Builtins.h:176
const OptionalFlag & hasAlternativeForm() const
Definition: FormatString.h:525
QualType withConst() const
Retrieves a version of this type with const applied.
ObjCStringFormatFamily
CanQualType LongLongTy
Definition: ASTContext.h:1004
An instance of this class is created to represent a function declaration or definition.
Definition: Decl.h:1697
NamespaceDecl * getStdNamespace() const
const char * getSpelling() const
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2269
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
The receiver is an object instance.
Definition: ExprObjC.h:1054
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:3513
Expr * getLHS() const
Definition: Expr.h:3314
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static void CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc)
CheckReturnStackAddr - Check if a return statement returns the address of a stack variable...
SourceLocation getRParenLoc() const
Definition: Expr.h:2345
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:344
#define BUILTIN_ROW(x)
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
CanQualType OCLQueueTy
Definition: ASTContext.h:1022
Smart pointer class that efficiently represents Objective-C method names.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2283
QualType getElementType() const
Definition: Type.h:5662
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
CanQualType VoidPtrTy
Definition: ASTContext.h:1012
QualType getPointeeType() const
Definition: Type.h:2296
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
A (possibly-)qualified type.
Definition: Type.h:653
bool isBlockPointerType() const
Definition: Type.h:5950
StringKind getKind() const
Definition: Expr.h:1597
bool isArrayType() const
Definition: Type.h:5991
bool isMemberPointerType() const
Definition: Type.h:5973
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2483
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different overload formats specified ...
const ScanfConversionSpecifier & getConversionSpecifier() const
Definition: FormatString.h:597
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2278
Selector getSelector() const
Definition: ExprObjC.cpp:312
static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall)
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:1856
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:767
static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
Defines enumerations for the type traits support.
FormatStringType
Definition: Sema.h:10354
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
Definition: Type.h:989
bool isSuperReceiver() const
Definition: ExprObjC.h:739
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2994
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3920
bool containsNonAsciiOrNull() const
Definition: Expr.h:1607
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
Stmt - This represents one statement.
Definition: Stmt.h:66
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2266
static Optional< int > GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message)
Expr * getBitWidth() const
Definition: Decl.h:2556
Kind getKind() const
Definition: Type.h:2164
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3056
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition: Expr.cpp:1040
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:456
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:790
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
Definition: Decl.h:2671
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1893
C Language Family Type Representation.
Defines the SourceManager interface.
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
Definition: ExprObjC.cpp:333
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:815
bool isRecordType() const
Definition: Type.h:6015
bool isAscii() const
Definition: Expr.h:1600
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
Expr * getBase() const
Definition: Expr.h:2477
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1880
const Type * getTypeForDecl() const
Definition: Decl.h:2784
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1427
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1270
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:580
bool isVariadic() const
Definition: Type.h:3615
arg_iterator arg_begin()
Definition: ExprCXX.h:1353
void setType(QualType t)
Definition: Expr.h:129
Opcode getOpcode() const
Definition: Expr.h:3026
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1665
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
Expr * getLowerBound()
Get lower bound of array section.
Definition: ExprOpenMP.h:91
const RecordDecl * getParent() const
getParent - Returns the parent of this field declaration, which is the struct in which this field is ...
Definition: Decl.h:2648
The base class of the type hierarchy.
Definition: Type.h:1351
bool isVector() const
Definition: APValue.h:188
#define log2(__x)
Definition: tgmath.h:986
CanQualType LongTy
Definition: ASTContext.h:1004
bool isClkEventT() const
Definition: Type.h:6104
CanQualType getNSUIntegerType() const
Definition: ASTContext.h:1642
NSDictionaryMethodKind
Enumerates the NSDictionary/NSMutableDictionary methods used to generate literals and to apply some c...
Definition: NSAPI.h:100
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2558
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:505
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:45
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1239
Wrapper for source info for typedefs.
Definition: TypeLoc.h:665
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
QualType withConst() const
Definition: Type.h:818
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:671
const NestedNameSpecifier * Specifier
A container of type source information.
Definition: Decl.h:86
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call)
Returns true if pipe element type is different from the pointer.
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:1645
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4035
static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount)
Checks that a call expression&#39;s argument count is the desired number.
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
CanQualType HalfTy
Definition: ASTContext.h:1008
QualType getElementType() const
Definition: Type.h:2593
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:491
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1840
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:806
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
QualType getReturnType() const
Definition: Decl.h:2207
ScopeFlags
ScopeFlags - These are bitfields that are or&#39;d together when creating a scope, which defines the sort...
Definition: Scope.h:43
DiagnosticsEngine & Diags
Definition: Sema.h:318
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2637
unsigned getNumParams() const
Definition: Type.h:3489
bool isEnumeralType() const
Definition: Type.h:6019
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const AstTypeMatcher< PointerType > pointerType
Matches pointer types, but does not match Objective-C object pointer types.
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3426
APFloat & getComplexFloatReal()
Definition: APValue.h:233
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6305
Extra information about a function prototype.
Definition: Type.h:3387
const OptionalFlag & hasThousandsGrouping() const
Definition: FormatString.h:520
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const
Produce a unique representation of the given statement.
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:734
bool isInvalidDecl() const
Definition: DeclBase.h:546
Like System, but searched after the system directories.
bool isAddrLabelDiff() const
Definition: APValue.h:193
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1513
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1194
Defines the clang::Expr interface and subclasses for C++ expressions.
ObjCInterfaceDecl * NSDictionaryDecl
The declaration of the Objective-C NSDictionary class.
Definition: Sema.h:869
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat, etc and warns if it&#39;s a comparison.
Parse and apply any fixits to the source.
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2276
bool isVariableArrayType() const
Definition: Type.h:6003
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:3433
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:670
PipeType - OpenCL20.
Definition: Type.h:5648
static bool requiresParensToAddCast(const Expr *E)
ArgType getArgType(ASTContext &Ctx) const
static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, Expr *BlockArg, unsigned NumNonVarArgs)
OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all &#39;local void*&#39; parameter of passed blo...
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:265
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:2865
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3488
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
Definition: SemaExpr.cpp:660
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:291
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists...
Definition: Decl.h:3380
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3431
One of these records is kept for each identifier that is lexed.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:833
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:859
Expr * getFalseExpr() const
Definition: Expr.h:3312
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:255
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:3533
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
QualType getPointeeType() const
Definition: Type.h:2400
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7393
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3496
bool isUTF8() const
Definition: Expr.h:1602
bool isCharType() const
Definition: Type.cpp:1750
field_range fields() const
Definition: Decl.h:3619
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2467
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:1639
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static int classifyConstantValue(Expr *Constant)
bool isReferenceType() const
Definition: Type.h:5954
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2288
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:404
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:391
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:926
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6136
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: Decl.h:3773
Expr * getSubExpr()
Definition: Expr.h:2761
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
Definition: Expr.h:5225
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1022
static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
SourceLocation getQuestionLoc() const
Definition: Expr.h:3258
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
Definition: ExprObjC.h:171
unsigned getCharByteWidth() const
Definition: Expr.h:1591
bool isFloat() const
Definition: APValue.h:184
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:5872
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6219
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
IdentifierTable & Idents
Definition: ASTContext.h:537
static Optional< int > GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message)
MatchKind matchesType(ASTContext &C, QualType argTy) const
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:107
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2167
bool isUnarySelector() const
Describes an C or C++ initializer list.
Definition: Expr.h:3872
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const
EvaluateAsBooleanCondition - Return true if this is a constant which we we can fold and convert to a ...
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, unsigned Start, unsigned End)
BinaryOperatorKind
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2545
ForStmt - This represents a &#39;for (init;cond;inc)&#39; stmt.
Definition: Stmt.h:1207
unsigned getLength() const
Definition: Expr.h:1590
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:3072
Represents the results of name lookup.
Definition: Lookup.h:32
PtrTy get() const
Definition: Ownership.h:162
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1171
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:573
uint32_t Offset
Definition: CacheTokens.cpp:43
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2166
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:119
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
bool hasValidLengthModifier(const TargetInfo &Target) const
static bool isNonNullType(ASTContext &ctx, QualType type)
Determine whether the given type has a non-null nullability annotation.
unsigned LayoutCompatible
If true, Type should be compared with other expression&#39;s types for layout-compatibility.
Definition: Sema.h:10455
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:857
child_range children()
Definition: Stmt.cpp:226
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:3782
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:635
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2985
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
Definition: Decl.h:3390
bool isComplexFloat() const
Definition: APValue.h:186
QualType getExceptionObjectType(QualType T) const
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isComplexInt() const
Definition: APValue.h:185
bool isArrow() const
Definition: Expr.h:2582
Defines the Diagnostic-related interfaces.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2465
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
Values of this type can never be null.
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, const ASTContext *Context=nullptr) const
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5718
field_iterator field_begin() const
Definition: Decl.cpp:3960
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3656
bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:3610
NSSetMethodKind
Enumerates the NSMutableSet/NSOrderedSet methods used to apply some checks.
Definition: NSAPI.h:125
bool isInt() const
Definition: APValue.h:183
static QualType GetExprType(const Expr *E)
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body. ...
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2710
base_class_iterator bases_begin()
Definition: DeclCXX.h:780
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.h:1646
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
const LangOptions & getLangOpts() const
Definition: Sema.h:1193
bool isUnsigned() const
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name, with source-location information.
Definition: Expr.h:1060
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:167
bool isScalarType() const
Definition: Type.h:6204
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:7924
An ordinary object is located at an address in memory.
Definition: Specifiers.h:123
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable)...
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17.6 - Check the argument to the get_kernel_work_group_size and get_kernel_prefe...
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:3002
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1716
Expression is a GNU-style __null constant.
Definition: Expr.h:691
static void diagnoseRetainCycle(Sema &S, Expr *capturer, RetainCycleOwner &owner)
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
APSInt & getComplexIntReal()
Definition: APValue.h:217
CanQualType UnsignedCharTy
Definition: ASTContext.h:1005
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:869
std::string getRepresentativeTypeName(ASTContext &C) const
static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
Iterator for iterating over Stmt * arrays that contain only Expr *.
Definition: Stmt.h:332
const OptionalFlag & hasLeadingZeros() const
Definition: FormatString.h:526
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e.g., it is an unsigned integer type or a vector.
Definition: Type.cpp:1870
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
This object can be modified without requiring retains or releases.
Definition: Type.h:173
param_iterator param_begin()
Definition: Decl.h:2179
arg_iterator arg_end()
Definition: Expr.h:2309
APValue & getVectorElt(unsigned I)
Definition: APValue.h:260
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1735
NodeId Parent
Definition: ASTDiff.cpp:192
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:216
Provides definitions for the various language-specific address spaces.
Decl * getNextDeclInContext()
Definition: DeclBase.h:422
OpenMP 4.0 [2.4, Array Sections].
Definition: ExprOpenMP.h:45
const OptionalFlag & hasPlusPrefix() const
Definition: FormatString.h:524
bool hasAttr() const
Definition: DeclBase.h:535
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3269
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:274
StringRef getString() const
Definition: Expr.h:1557
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2381
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1590
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3268
bool isDynamicClass() const
Definition: DeclCXX.h:751
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3172
CastKind
CastKind - The kind of operation required for a conversion.
QualType getPromotionType() const
getPromotionType - Return the integer type that enumerators should promote to.
Definition: Decl.h:3356
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.cpp:290
static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx)
Returns true if pipe element type is different from the pointer.
AbsoluteValueKind
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2031
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to...
Definition: Expr.cpp:1762
static const Expr * EvalVal(const Expr *E, SmallVectorImpl< const DeclRefExpr *> &refVars, const Decl *ParentDecl)
EvalVal - This function is complements EvalAddr in the mutual recursion.
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:86
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:6270
arg_iterator arg_end()
Definition: ExprCXX.h:1354
SourceLocation getLocation() const
Definition: Expr.h:1049
bool isEnabled(llvm::StringRef Ext) const
Definition: OpenCLOptions.h:39
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:2847
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Scope * getCurScope() const
Retrieve the parser&#39;s current scope.
Definition: Sema.h:10524
static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:2942
Exposes information about the current target.
Definition: TargetInfo.h:54
NSArrayMethodKind
Enumerates the NSArray/NSMutableArray methods used to generate literals and to apply some checks...
Definition: NSAPI.h:76
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we&#39;re targeting...
Expr * getCond() const
Definition: Expr.h:3303
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4200
static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, CallExpr *TheCall, unsigned SizeIdx, unsigned DstSizeIdx)
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3695
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:627
Expr - This represents one expression.
Definition: Expr.h:106
Defines the clang::LangOptions interface.
const OptionalFlag & isLeftJustified() const
Definition: FormatString.h:523
Allow any unmodeled side effect.
Definition: Expr.h:598
SourceLocation End
Represents a character-granular source range.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:104
void setCallee(Expr *F)
Definition: Expr.h:2251
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
void EvaluateForOverflow(const ASTContext &Ctx) const
const FunctionProtoType * T
static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, SourceLocation CC)
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm...
Definition: TargetInfo.h:1040
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6368
bool isObjCRetainableType() const
Definition: Type.cpp:3824
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
Definition: Decl.cpp:1030
static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg)
OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local void*, which is a requirem...
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:4851
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:86
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2620
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
unsigned getNumInits() const
Definition: Expr.h:3902
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3347
This scope corresponds to an SEH except.
Definition: Scope.h:123
Defines an enumeration for C++ overloaded operators.
const Expr * getCallee() const
Definition: Expr.h:2249
bool isNullPtrType() const
Definition: Type.h:6182
field_iterator field_end() const
Definition: Decl.h:3622
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:288
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:6250
DeclContext * getDeclContext()
Definition: DeclBase.h:425
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:731
bool isAnyComplexType() const
Definition: Type.h:6023
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:425
CanQualType ShortTy
Definition: ASTContext.h:1004
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1165
const OptionalAmount & getFieldWidth() const
Definition: FormatString.h:390
void removeLocalConst()
Definition: Type.h:5812
void removeLocalVolatile()
Definition: Type.h:5820
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
Defines the clang::TypeLoc interface and its subclasses.
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:3800
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1800
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
QualType getType() const
Definition: Expr.h:128
bool isWide() const
Definition: Expr.h:1601
Expr * getElement(unsigned Index)
getElement - Return the Element at the specified index.
Definition: ExprObjC.h:213
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr *> Args, SourceLocation CallSiteLoc)
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:422
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:925
static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call)
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:903
bool isInvalid() const
Definition: Ownership.h:158
SourceLocation getRBracketLoc() const
Definition: Expr.h:2183
SourceLocation getEnd() const
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1717
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef< const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg)
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1333
Represents a GCC generic vector type.
Definition: Type.h:2914
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1187
static OpenCLAccessAttr * getOpenCLArgAccess(const Decl *D)
Returns OpenCL access qual.
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2595
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1041
unsigned getNumArgs() const
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6263
bool capturesVariable(const VarDecl *var) const
Definition: Decl.cpp:4095
ValueDecl * getDecl()
Definition: Expr.h:1041
APSInt & getComplexIntImag()
Definition: APValue.h:225
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1347
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool pruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr.
Definition: Expr.h:2922
QualType withoutLocalFastQualifiers() const
Definition: Type.h:874
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:444
static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, const NamedDecl *ND)
Check whether this array fits the idiom of a size-one tail padded array member of a struct...
const LengthModifier & getLengthModifier() const
Definition: FormatString.h:386
QualType getType() const
Definition: DeclObjC.h:846
const SourceManager & SM
Definition: Format.cpp:1337
static StringRef getIdentifier(const Token &Tok)
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, bool IsPolyUnsigned, bool IsInt64Long)
getNeonEltType - Return the QualType corresponding to the elements of the vector type specified by th...
CanQualType getNSIntegerType() const
Definition: ASTContext.h:1651
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:233
static const Expr * getStrlenExprArg(const Expr *E)
static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall)
SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: ExprObjC.h:1341
CanQualType SignedCharTy
Definition: ASTContext.h:1004
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue)
Given a type tag expression find the type tag itself.
static CharSourceRange getCharRange(SourceRange R)
bool isVoidPointerType() const
Definition: Type.cpp:426
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5777
static const Expr * EvalAddr(const Expr *E, SmallVectorImpl< const DeclRefExpr *> &refVars, const Decl *ParentDecl)
EvalAddr - EvalAddr and EvalVal are mutually recursive functions that check if the expression in a re...
RecordDecl * getDecl() const
Definition: Type.h:3986
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition: Sema.h:10461
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call)
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclBase.h:408
EltType getEltType() const
Defines the clang::OpenCLOptions class.
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
There is no lifetime qualification on this type.
Definition: Type.h:169
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:868
Enumerates target-specific builtins in their own namespaces within namespace clang.
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:3601
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver. ...
Definition: ExprObjC.h:1328
CanQualType BuiltinFnTy
Definition: ASTContext.h:1014
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:180
Kind
QualType getCanonicalType() const
Definition: Type.h:5757
not a target-specific vector type
Definition: Type.h:2918
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:144
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4969
bool isImplicitProperty() const
Definition: ExprObjC.h:667
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
Definition: Expr.h:191
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
ASTContext & getASTContext() const
Definition: Sema.h:1200
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner)
Consider whether capturing the given variable can possibly lead to a retain cycle.
static void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, Expr *Element, unsigned ElementKind)
Check a single element within a collection literal against the target element type.
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3276
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, SourceLocation CC, QualType T)
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl *> Parameters, bool CheckParameterNames)
Helpers for dealing with blocks and functions.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4002
SourceLocation getOperatorLoc() const
Definition: Expr.h:3023
std::pair< SourceLocation, SourceLocation > getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:5834
Expression is not a Null pointer constant.
Definition: Expr.h:675
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:761
Expr * getSubExpr() const
Definition: Expr.h:1744
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1874
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle...
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
CastKind getCastKind() const
Definition: Expr.h:2757
std::string getNameAsString() const
getNameAsString - Get a human-readable name for the declaration, even if it is one of the special kin...
Definition: Decl.h:285
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:342
APFloat & getFloat()
Definition: APValue.h:209
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:121
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1722
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1964
static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool)
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2321
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall)
SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
SourceLocation getSuperLoc() const
Retrieve the location of the &#39;super&#39; keyword for a class or instance message to &#39;super&#39;, otherwise an invalid source location.
Definition: ExprObjC.h:1247
CanQualType FloatTy
Definition: ASTContext.h:1007
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2190
static void checkObjCArrayLiteral(Sema &S, QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
bool isPascal() const
Definition: Expr.h:1605
static void DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, and corresponding __opencl_atomic_* for OpenCL 2.0.
Definition: Expr.h:5103
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:706
CanQualType VoidTy
Definition: ASTContext.h:996
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
CheckBoolLikeConversion - Check conversion of given expression to boolean.
Class representing optional flags with location and representation information.
Definition: FormatString.h:34
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
Look up any declaration with any name.
Definition: Sema.h:3034
arg_range arguments()
Definition: Expr.h:2303
bool isKnownToHaveBooleanValue() const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:135
bool isObjCObjectPointerType() const
Definition: Type.h:6039
bool isAnyPointerType() const
Definition: Type.h:5946
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static bool isBlockPointer(Expr *Arg)
bool FormatStringHasSArg(const StringLiteral *FExpr)
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:746
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2822
bool isFunctionProtoType() const
Definition: Type.h:1743
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool isLValue() const
Definition: APValue.h:187
TypeClass getTypeClass() const
Definition: Type.h:1613
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:2931
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1909
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3105
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have &#39;.c_str()&#39; called on it.
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1302
static bool IsEnumConstOrFromMacro(Sema &S, Expr *E)
bool isVectorType() const
Definition: Type.h:6027
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:929
Assigning into this object requires a lifetime extension.
Definition: Type.h:186
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclObjC.h:323
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:450
static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call)
We are currently in the filter expression of an SEH except block.
Definition: Scope.h:126
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2214
LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
Definition: CharInfo.h:100
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:971
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1018
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat &#39;semantics&#39; for the specified scalar floating point type.
const PrintfConversionSpecifier & getConversionSpecifier() const
Definition: FormatString.h:496
Expr * getLHS() const
Definition: Expr.h:3029
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3191
Defines various enumerations that describe declaration and type specifiers.
StringRef getName() const
Return the actual identifier string.
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition: ExprObjC.h:1206
CanQualType UnsignedShortTy
Definition: ASTContext.h:1005
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Canon=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2802
QualType withVolatile() const
Definition: Type.h:826
CanQualType CharTy
Definition: ASTContext.h:998
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:8377
bool isPipeType() const
Definition: Type.h:6123
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:556
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1256
SourceLocation getLocation() const
Definition: ExprObjC.h:726
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
PropertyAttributeKind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:869
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:224
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1216
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type &#39;Type&#39;, insert an implicit cast.
Definition: Sema.cpp:466
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments for this type.
Definition: Type.h:5548
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
bool isSEHExceptScope() const
Determine whether this scope is a SEH &#39;__except&#39; block.
Definition: Scope.h:436
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:9454
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:15182
BinaryOperator::Opcode getOpcode(const SymExpr *SE)
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1006
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:116
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
SourceLocation getSemiLoc() const
Definition: Stmt.h:577
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change...
Definition: TargetCXXABI.h:216
DeclarationName - The name of a declaration.
StmtClass getStmtClass() const
Definition: Stmt.h:378
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:979
bool isBooleanType() const
Definition: Type.h:6232
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1317
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
Definition: Expr.h:682
U cast(CodeGen::Address addr)
Definition: Address.h:109
static bool isSetterLikeSelector(Selector sel)
Check for a keyword selector that starts with the word &#39;add&#39; or &#39;set&#39;.
A set of unresolved declarations.
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:5196
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:731
EnumDecl - Represents an enum.
Definition: Decl.h:3239
Expression is a C++11 nullptr.
Definition: Expr.h:688
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
const OptionalFlag & isPrivate() const
Definition: FormatString.h:529
Flags to identify the types for overloaded Neon builtins.
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1307
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
Optional< LengthModifier > getCorrectedLengthModifier() const
static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner)
static bool IsSameCharType(QualType T1, QualType T2)
SyntaxTree::Impl & Tree
Definition: ASTDiff.cpp:193
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:1600
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:919
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
SemaConvertVectorExpr - Handle __builtin_convertvector.
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2552
param_iterator param_end()
Definition: Decl.h:2180
static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall)
llvm::APInt getValue() const
Definition: Expr.h:1279
bool isMacroID() const
Decl * getCalleeDecl()
Definition: Expr.cpp:1220
Represents a pointer to an Objective C object.
Definition: Type.h:5440
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:150
unsigned getByteLength() const
Definition: Expr.h:1589
Pointer to a block type.
Definition: Type.h:2385
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
unsigned getIntWidth(QualType T) const
static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, CallExpr *Call)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3976
Complex values, per C99 6.2.5p11.
Definition: Type.h:2223
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument&#39;s expansion into the function-lik...
static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call)
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2121
StringLiteralCheckType
bool isUTF32() const
Definition: Expr.h:1604
QualType getCanonicalTypeInternal() const
Definition: Type.h:2107
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:210
ObjCLiteralKind
Definition: Sema.h:2674
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:3227
bool isReserveIDT() const
Definition: Type.h:6112
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6191
static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntType)
Diagnose integer type and any valid implicit conversion to it.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1005
ArgType getArgType(ASTContext &Ctx) const
static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call)
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1074
T * getAttr() const
Definition: DeclBase.h:531
const llvm::APInt & getSize() const
Definition: Type.h:2636
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2011
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
Definition: Sema.cpp:1166
bool isAtomicType() const
Definition: Type.h:6052
static bool isKnownToHaveUnsignedValue(Expr *E)
bool isFunctionType() const
Definition: Type.h:5938
static unsigned RFT(unsigned t, bool shift=false, bool ForceQuad=false)
bool isObjCQualifiedIdType() const
Definition: Type.h:6056
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1326
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:707
static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type. ...
const OptionalAmount & getPrecision() const
Definition: FormatString.h:505
Opcode getOpcode() const
Definition: Expr.h:1741
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3061
bool isInteger() const
Definition: Type.h:2177
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2190
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1934
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo)
Retrieve the C type corresponding to type tag TypeExpr.
The template argument is a type.
Definition: TemplateBase.h:60
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:90
const OptionalFlag & isPublic() const
Definition: FormatString.h:530
ObjCInterfaceDecl * NSArrayDecl
The declaration of the Objective-C NSArray class.
Definition: Sema.h:863
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:1335
const Expr * getBase() const
Definition: ExprObjC.h:547
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3022
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3597
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
Represents a base class of a C++ class.
Definition: DeclCXX.h:191
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2007
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool isObjCObjectType() const
Definition: Type.h:6043
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1986
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
const OptionalFlag & hasSpacePrefix() const
Definition: FormatString.h:527
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2174
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:517
static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr)
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:239
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Reading or writing from this object requires a barrier call.
Definition: Type.h:183
bool isQueueT() const
Definition: Type.h:6108
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
bool isFreeIvar() const
Definition: ExprObjC.h:552
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
QualType getParamType(unsigned i) const
Definition: Type.h:3491
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:685
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef< const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, Sema::VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset)
static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body, and it is located on the same line.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2387
static bool HasEnumType(Expr *E)
Defines the clang::SourceLocation class and associated facilities.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5798
Provides definitions for the atomic synchronization scopes.
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool hasUnaligned() const
Definition: Type.h:312
APFloat & getComplexFloatImag()
Definition: APValue.h:241
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g., it is an signed integer type or a vector.
Definition: Type.cpp:1830
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
Compatible - the types are compatible according to the standard.
Definition: Sema.h:9355
Expr * getTrueExpr() const
Definition: Expr.h:3307
bool isVoidType() const
Definition: Type.h:6169
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2856
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:1696
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5745
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:3407
Expr * getRHS() const
Definition: Expr.h:3315
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1964
WhileStmt - This represents a &#39;while&#39; stmt.
Definition: Stmt.h:1102
static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall)
SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:539
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:328
bool isRValue() const
Definition: Expr.h:250
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:127
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2143
bool isVariadic() const
Definition: DeclObjC.h:454
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
SourceManager & getSourceManager() const
Definition: Sema.h:1198
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:265
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1509
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2209
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
Definition: Decl.h:3364
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:270
ExprResult ExprError()
Definition: Ownership.h:267
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:930
CanQualType IntTy
Definition: ASTContext.h:1004
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1858
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:734
bool isUnion() const
Definition: Decl.h:3165
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
Expr * getRHS() const
Definition: Expr.h:3031
static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool isPointerType() const
Definition: Type.h:5942
SourceManager & SourceMgr
Definition: Sema.h:319
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:96
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:64
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type...
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:586
QualType getType() const
Definition: Decl.h:638
#define true
Definition: stdbool.h:32
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:111
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
bool isFloatingType() const
Definition: Type.cpp:1877
bool isUTF16() const
Definition: Expr.h:1603
const Expr * getBase() const
Definition: ExprObjC.h:719
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:316
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
CanQualType BoolTy
Definition: ASTContext.h:997
static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth)
Pseudo-evaluate the given integer expression, estimating the range of values it might take...
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:789
APSInt & getInt()
Definition: APValue.h:201
CanQualType DoubleTy
Definition: ASTContext.h:1007
static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth)
static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
Describes an entity that is being initialized.
bool isFunctionPointerType() const
Definition: Type.h:5966
bool isInStdNamespace() const
Definition: DeclBase.cpp:359
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition: ExprObjC.h:1194
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:2910
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:277
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3075
SourceLocation getBegin() const
Optional< ConversionSpecifier > getStandardSpecifier() const
const LangOptions & getLangOpts() const
Definition: ASTContext.h:688
static Expr * findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner)
Check whether the given argument is a block which captures a variable.
static Optional< int > GetNSMutableDictionaryArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2618
This class handles loading and caching of source files into memory.
bool isUnsignedInteger() const
Definition: Type.h:2185
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition: Types.cpp:120
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Definition: Expr.h:673
Attr - This represents one attribute.
Definition: Attr.h:43
SourceLocation getLocation() const
Definition: DeclBase.h:416
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:3066
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:11064
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
CanQualType OCLClkEventTy
Definition: ASTContext.h:1021
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:405
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1223
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2434
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
CanQualType UnsignedIntTy
Definition: ASTContext.h:1005
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, ASTContext &Context)
A helper function to get the alignment of a Decl referred to by DeclRefExpr or MemberExpr.
Expr * getBase()
An array section can be written only as Base[LowerBound:Length].
Definition: ExprOpenMP.h:82
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1070
unsigned getVectorLength() const
Definition: APValue.h:268