clang  10.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements extra semantic analysis beyond what is enforced
10 // by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
33 #include "clang/AST/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
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/SaveAndRestore.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
103  unsigned ByteNo) const {
104  return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105  Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking. Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111  unsigned argCount = call->getNumArgs();
112  if (argCount == desiredArgCount) return false;
113 
114  if (argCount < desiredArgCount)
115  return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116  << 0 /*function call*/ << desiredArgCount << argCount
117  << call->getSourceRange();
118 
119  // Highlight all the excess arguments.
120  SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121  call->getArg(argCount - 1)->getEndLoc());
122 
123  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124  << 0 /*function call*/ << desiredArgCount << argCount
125  << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131  if (checkArgCount(S, TheCall, 2))
132  return true;
133 
134  // First argument should be an integer.
135  Expr *ValArg = TheCall->getArg(0);
136  QualType Ty = ValArg->getType();
137  if (!Ty->isIntegerType()) {
138  S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139  << ValArg->getSourceRange();
140  return true;
141  }
142 
143  // Second argument should be a constant string.
144  Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145  StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146  if (!Literal || !Literal->isAscii()) {
147  S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148  << StrArg->getSourceRange();
149  return true;
150  }
151 
152  TheCall->setType(Ty);
153  return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157  // We need at least one argument.
158  if (TheCall->getNumArgs() < 1) {
159  S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160  << 0 << 1 << TheCall->getNumArgs()
161  << TheCall->getCallee()->getSourceRange();
162  return true;
163  }
164 
165  // All arguments should be wide string literals.
166  for (Expr *Arg : TheCall->arguments()) {
167  auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168  if (!Literal || !Literal->isWide()) {
169  S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170  << Arg->getSourceRange();
171  return true;
172  }
173  }
174 
175  return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181  if (checkArgCount(S, TheCall, 1))
182  return true;
183 
184  ExprResult Arg(TheCall->getArg(0));
185  QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186  if (ResultType.isNull())
187  return true;
188 
189  TheCall->setArg(0, Arg.get());
190  TheCall->setType(ResultType);
191  return false;
192 }
193 
194 /// Check the number of arguments and set the result type to
195 /// the argument type.
196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197  if (checkArgCount(S, TheCall, 1))
198  return true;
199 
200  TheCall->setType(TheCall->getArg(0)->getType());
201  return false;
202 }
203 
204 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
205 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
206 /// type (but not a function pointer) and that the alignment is a power-of-two.
207 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
208  if (checkArgCount(S, TheCall, 2))
209  return true;
210 
211  clang::Expr *Source = TheCall->getArg(0);
212  bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
213 
214  auto IsValidIntegerType = [](QualType Ty) {
215  return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
216  };
217  QualType SrcTy = Source->getType();
218  // We should also be able to use it with arrays (but not functions!).
219  if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
220  SrcTy = S.Context.getDecayedType(SrcTy);
221  }
222  if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
223  SrcTy->isFunctionPointerType()) {
224  // FIXME: this is not quite the right error message since we don't allow
225  // floating point types, or member pointers.
226  S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
227  << SrcTy;
228  return true;
229  }
230 
231  clang::Expr *AlignOp = TheCall->getArg(1);
232  if (!IsValidIntegerType(AlignOp->getType())) {
233  S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
234  << AlignOp->getType();
235  return true;
236  }
237  Expr::EvalResult AlignResult;
238  unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
239  // We can't check validity of alignment if it is type dependent.
240  if (!AlignOp->isInstantiationDependent() &&
241  AlignOp->EvaluateAsInt(AlignResult, S.Context,
243  llvm::APSInt AlignValue = AlignResult.Val.getInt();
244  llvm::APSInt MaxValue(
245  llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
246  if (AlignValue < 1) {
247  S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
248  return true;
249  }
250  if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
251  S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
252  << MaxValue.toString(10);
253  return true;
254  }
255  if (!AlignValue.isPowerOf2()) {
256  S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
257  return true;
258  }
259  if (AlignValue == 1) {
260  S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
261  << IsBooleanAlignBuiltin;
262  }
263  }
264 
267  SourceLocation(), Source);
268  if (SrcArg.isInvalid())
269  return true;
270  TheCall->setArg(0, SrcArg.get());
271  ExprResult AlignArg =
273  S.Context, AlignOp->getType(), false),
274  SourceLocation(), AlignOp);
275  if (AlignArg.isInvalid())
276  return true;
277  TheCall->setArg(1, AlignArg.get());
278  // For align_up/align_down, the return type is the same as the (potentially
279  // decayed) argument type including qualifiers. For is_aligned(), the result
280  // is always bool.
281  TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
282  return false;
283 }
284 
285 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
286  if (checkArgCount(S, TheCall, 3))
287  return true;
288 
289  // First two arguments should be integers.
290  for (unsigned I = 0; I < 2; ++I) {
291  ExprResult Arg = TheCall->getArg(I);
292  QualType Ty = Arg.get()->getType();
293  if (!Ty->isIntegerType()) {
294  S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
295  << Ty << Arg.get()->getSourceRange();
296  return true;
297  }
299  S.getASTContext(), Ty, /*consume*/ false);
300  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
301  if (Arg.isInvalid())
302  return true;
303  TheCall->setArg(I, Arg.get());
304  }
305 
306  // Third argument should be a pointer to a non-const integer.
307  // IRGen correctly handles volatile, restrict, and address spaces, and
308  // the other qualifiers aren't possible.
309  {
310  ExprResult Arg = TheCall->getArg(2);
311  QualType Ty = Arg.get()->getType();
312  const auto *PtrTy = Ty->getAs<PointerType>();
313  if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
314  !PtrTy->getPointeeType().isConstQualified())) {
315  S.Diag(Arg.get()->getBeginLoc(),
316  diag::err_overflow_builtin_must_be_ptr_int)
317  << Ty << Arg.get()->getSourceRange();
318  return true;
319  }
321  S.getASTContext(), Ty, /*consume*/ false);
322  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
323  if (Arg.isInvalid())
324  return true;
325  TheCall->setArg(2, Arg.get());
326  }
327  return false;
328 }
329 
330 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
331  if (checkArgCount(S, BuiltinCall, 2))
332  return true;
333 
334  SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
335  Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
336  Expr *Call = BuiltinCall->getArg(0);
337  Expr *Chain = BuiltinCall->getArg(1);
338 
339  if (Call->getStmtClass() != Stmt::CallExprClass) {
340  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
341  << Call->getSourceRange();
342  return true;
343  }
344 
345  auto CE = cast<CallExpr>(Call);
346  if (CE->getCallee()->getType()->isBlockPointerType()) {
347  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
348  << Call->getSourceRange();
349  return true;
350  }
351 
352  const Decl *TargetDecl = CE->getCalleeDecl();
353  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
354  if (FD->getBuiltinID()) {
355  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
356  << Call->getSourceRange();
357  return true;
358  }
359 
360  if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
361  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
362  << Call->getSourceRange();
363  return true;
364  }
365 
366  ExprResult ChainResult = S.UsualUnaryConversions(Chain);
367  if (ChainResult.isInvalid())
368  return true;
369  if (!ChainResult.get()->getType()->isPointerType()) {
370  S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
371  << Chain->getSourceRange();
372  return true;
373  }
374 
375  QualType ReturnTy = CE->getCallReturnType(S.Context);
376  QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
377  QualType BuiltinTy = S.Context.getFunctionType(
378  ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
379  QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
380 
381  Builtin =
382  S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
383 
384  BuiltinCall->setType(CE->getType());
385  BuiltinCall->setValueKind(CE->getValueKind());
386  BuiltinCall->setObjectKind(CE->getObjectKind());
387  BuiltinCall->setCallee(Builtin);
388  BuiltinCall->setArg(1, ChainResult.get());
389 
390  return false;
391 }
392 
393 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
394 /// __builtin_*_chk function, then use the object size argument specified in the
395 /// source. Otherwise, infer the object size using __builtin_object_size.
396 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
397  CallExpr *TheCall) {
398  // FIXME: There are some more useful checks we could be doing here:
399  // - Analyze the format string of sprintf to see how much of buffer is used.
400  // - Evaluate strlen of strcpy arguments, use as object size.
401 
402  if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
403  isConstantEvaluated())
404  return;
405 
406  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
407  if (!BuiltinID)
408  return;
409 
410  unsigned DiagID = 0;
411  bool IsChkVariant = false;
412  unsigned SizeIndex, ObjectIndex;
413  switch (BuiltinID) {
414  default:
415  return;
416  case Builtin::BI__builtin___memcpy_chk:
417  case Builtin::BI__builtin___memmove_chk:
418  case Builtin::BI__builtin___memset_chk:
419  case Builtin::BI__builtin___strlcat_chk:
420  case Builtin::BI__builtin___strlcpy_chk:
421  case Builtin::BI__builtin___strncat_chk:
422  case Builtin::BI__builtin___strncpy_chk:
423  case Builtin::BI__builtin___stpncpy_chk:
424  case Builtin::BI__builtin___memccpy_chk:
425  case Builtin::BI__builtin___mempcpy_chk: {
426  DiagID = diag::warn_builtin_chk_overflow;
427  IsChkVariant = true;
428  SizeIndex = TheCall->getNumArgs() - 2;
429  ObjectIndex = TheCall->getNumArgs() - 1;
430  break;
431  }
432 
433  case Builtin::BI__builtin___snprintf_chk:
434  case Builtin::BI__builtin___vsnprintf_chk: {
435  DiagID = diag::warn_builtin_chk_overflow;
436  IsChkVariant = true;
437  SizeIndex = 1;
438  ObjectIndex = 3;
439  break;
440  }
441 
442  case Builtin::BIstrncat:
443  case Builtin::BI__builtin_strncat:
444  case Builtin::BIstrncpy:
445  case Builtin::BI__builtin_strncpy:
446  case Builtin::BIstpncpy:
447  case Builtin::BI__builtin_stpncpy: {
448  // Whether these functions overflow depends on the runtime strlen of the
449  // string, not just the buffer size, so emitting the "always overflow"
450  // diagnostic isn't quite right. We should still diagnose passing a buffer
451  // size larger than the destination buffer though; this is a runtime abort
452  // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
453  DiagID = diag::warn_fortify_source_size_mismatch;
454  SizeIndex = TheCall->getNumArgs() - 1;
455  ObjectIndex = 0;
456  break;
457  }
458 
459  case Builtin::BImemcpy:
460  case Builtin::BI__builtin_memcpy:
461  case Builtin::BImemmove:
462  case Builtin::BI__builtin_memmove:
463  case Builtin::BImemset:
464  case Builtin::BI__builtin_memset:
465  case Builtin::BImempcpy:
466  case Builtin::BI__builtin_mempcpy: {
467  DiagID = diag::warn_fortify_source_overflow;
468  SizeIndex = TheCall->getNumArgs() - 1;
469  ObjectIndex = 0;
470  break;
471  }
472  case Builtin::BIsnprintf:
473  case Builtin::BI__builtin_snprintf:
474  case Builtin::BIvsnprintf:
475  case Builtin::BI__builtin_vsnprintf: {
476  DiagID = diag::warn_fortify_source_size_mismatch;
477  SizeIndex = 1;
478  ObjectIndex = 0;
479  break;
480  }
481  }
482 
483  llvm::APSInt ObjectSize;
484  // For __builtin___*_chk, the object size is explicitly provided by the caller
485  // (usually using __builtin_object_size). Use that value to check this call.
486  if (IsChkVariant) {
487  Expr::EvalResult Result;
488  Expr *SizeArg = TheCall->getArg(ObjectIndex);
489  if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
490  return;
491  ObjectSize = Result.Val.getInt();
492 
493  // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
494  } else {
495  // If the parameter has a pass_object_size attribute, then we should use its
496  // (potentially) more strict checking mode. Otherwise, conservatively assume
497  // type 0.
498  int BOSType = 0;
499  if (const auto *POS =
500  FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
501  BOSType = POS->getType();
502 
503  Expr *ObjArg = TheCall->getArg(ObjectIndex);
504  uint64_t Result;
505  if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
506  return;
507  // Get the object size in the target's size_t width.
508  const TargetInfo &TI = getASTContext().getTargetInfo();
509  unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
510  ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
511  }
512 
513  // Evaluate the number of bytes of the object that this call will use.
514  Expr::EvalResult Result;
515  Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
516  if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
517  return;
518  llvm::APSInt UsedSize = Result.Val.getInt();
519 
520  if (UsedSize.ule(ObjectSize))
521  return;
522 
523  StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
524  // Skim off the details of whichever builtin was called to produce a better
525  // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
526  if (IsChkVariant) {
527  FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
528  FunctionName = FunctionName.drop_back(std::strlen("_chk"));
529  } else if (FunctionName.startswith("__builtin_")) {
530  FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
531  }
532 
533  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
534  PDiag(DiagID)
535  << FunctionName << ObjectSize.toString(/*Radix=*/10)
536  << UsedSize.toString(/*Radix=*/10));
537 }
538 
539 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
540  Scope::ScopeFlags NeededScopeFlags,
541  unsigned DiagID) {
542  // Scopes aren't available during instantiation. Fortunately, builtin
543  // functions cannot be template args so they cannot be formed through template
544  // instantiation. Therefore checking once during the parse is sufficient.
545  if (SemaRef.inTemplateInstantiation())
546  return false;
547 
548  Scope *S = SemaRef.getCurScope();
549  while (S && !S->isSEHExceptScope())
550  S = S->getParent();
551  if (!S || !(S->getFlags() & NeededScopeFlags)) {
552  auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
553  SemaRef.Diag(TheCall->getExprLoc(), DiagID)
554  << DRE->getDecl()->getIdentifier();
555  return true;
556  }
557 
558  return false;
559 }
560 
561 static inline bool isBlockPointer(Expr *Arg) {
562  return Arg->getType()->isBlockPointerType();
563 }
564 
565 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
566 /// void*, which is a requirement of device side enqueue.
567 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
568  const BlockPointerType *BPT =
569  cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
570  ArrayRef<QualType> Params =
571  BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
572  unsigned ArgCounter = 0;
573  bool IllegalParams = false;
574  // Iterate through the block parameters until either one is found that is not
575  // a local void*, or the block is valid.
576  for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
577  I != E; ++I, ++ArgCounter) {
578  if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
579  (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
581  // Get the location of the error. If a block literal has been passed
582  // (BlockExpr) then we can point straight to the offending argument,
583  // else we just point to the variable reference.
584  SourceLocation ErrorLoc;
585  if (isa<BlockExpr>(BlockArg)) {
586  BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
587  ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
588  } else if (isa<DeclRefExpr>(BlockArg)) {
589  ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
590  }
591  S.Diag(ErrorLoc,
592  diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
593  IllegalParams = true;
594  }
595  }
596 
597  return IllegalParams;
598 }
599 
600 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
601  if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
602  S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
603  << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
604  return true;
605  }
606  return false;
607 }
608 
609 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
610  if (checkArgCount(S, TheCall, 2))
611  return true;
612 
613  if (checkOpenCLSubgroupExt(S, TheCall))
614  return true;
615 
616  // First argument is an ndrange_t type.
617  Expr *NDRangeArg = TheCall->getArg(0);
618  if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
619  S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
620  << TheCall->getDirectCallee() << "'ndrange_t'";
621  return true;
622  }
623 
624  Expr *BlockArg = TheCall->getArg(1);
625  if (!isBlockPointer(BlockArg)) {
626  S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
627  << TheCall->getDirectCallee() << "block";
628  return true;
629  }
630  return checkOpenCLBlockArgs(S, BlockArg);
631 }
632 
633 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
634 /// get_kernel_work_group_size
635 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
637  if (checkArgCount(S, TheCall, 1))
638  return true;
639 
640  Expr *BlockArg = TheCall->getArg(0);
641  if (!isBlockPointer(BlockArg)) {
642  S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
643  << TheCall->getDirectCallee() << "block";
644  return true;
645  }
646  return checkOpenCLBlockArgs(S, BlockArg);
647 }
648 
649 /// Diagnose integer type and any valid implicit conversion to it.
650 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
651  const QualType &IntType);
652 
654  unsigned Start, unsigned End) {
655  bool IllegalParams = false;
656  for (unsigned I = Start; I <= End; ++I)
657  IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
658  S.Context.getSizeType());
659  return IllegalParams;
660 }
661 
662 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
663 /// 'local void*' parameter of passed block.
665  Expr *BlockArg,
666  unsigned NumNonVarArgs) {
667  const BlockPointerType *BPT =
668  cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
669  unsigned NumBlockParams =
670  BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
671  unsigned TotalNumArgs = TheCall->getNumArgs();
672 
673  // For each argument passed to the block, a corresponding uint needs to
674  // be passed to describe the size of the local memory.
675  if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
676  S.Diag(TheCall->getBeginLoc(),
677  diag::err_opencl_enqueue_kernel_local_size_args);
678  return true;
679  }
680 
681  // Check that the sizes of the local memory are specified by integers.
682  return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
683  TotalNumArgs - 1);
684 }
685 
686 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
687 /// overload formats specified in Table 6.13.17.1.
688 /// int enqueue_kernel(queue_t queue,
689 /// kernel_enqueue_flags_t flags,
690 /// const ndrange_t ndrange,
691 /// void (^block)(void))
692 /// int enqueue_kernel(queue_t queue,
693 /// kernel_enqueue_flags_t flags,
694 /// const ndrange_t ndrange,
695 /// uint num_events_in_wait_list,
696 /// clk_event_t *event_wait_list,
697 /// clk_event_t *event_ret,
698 /// void (^block)(void))
699 /// int enqueue_kernel(queue_t queue,
700 /// kernel_enqueue_flags_t flags,
701 /// const ndrange_t ndrange,
702 /// void (^block)(local void*, ...),
703 /// uint size0, ...)
704 /// int enqueue_kernel(queue_t queue,
705 /// kernel_enqueue_flags_t flags,
706 /// const ndrange_t ndrange,
707 /// uint num_events_in_wait_list,
708 /// clk_event_t *event_wait_list,
709 /// clk_event_t *event_ret,
710 /// void (^block)(local void*, ...),
711 /// uint size0, ...)
712 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
713  unsigned NumArgs = TheCall->getNumArgs();
714 
715  if (NumArgs < 4) {
716  S.Diag(TheCall->getBeginLoc(),
717  diag::err_typecheck_call_too_few_args_at_least)
718  << 0 << 4 << NumArgs;
719  return true;
720  }
721 
722  Expr *Arg0 = TheCall->getArg(0);
723  Expr *Arg1 = TheCall->getArg(1);
724  Expr *Arg2 = TheCall->getArg(2);
725  Expr *Arg3 = TheCall->getArg(3);
726 
727  // First argument always needs to be a queue_t type.
728  if (!Arg0->getType()->isQueueT()) {
729  S.Diag(TheCall->getArg(0)->getBeginLoc(),
730  diag::err_opencl_builtin_expected_type)
731  << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
732  return true;
733  }
734 
735  // Second argument always needs to be a kernel_enqueue_flags_t enum value.
736  if (!Arg1->getType()->isIntegerType()) {
737  S.Diag(TheCall->getArg(1)->getBeginLoc(),
738  diag::err_opencl_builtin_expected_type)
739  << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
740  return true;
741  }
742 
743  // Third argument is always an ndrange_t type.
744  if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
745  S.Diag(TheCall->getArg(2)->getBeginLoc(),
746  diag::err_opencl_builtin_expected_type)
747  << TheCall->getDirectCallee() << "'ndrange_t'";
748  return true;
749  }
750 
751  // With four arguments, there is only one form that the function could be
752  // called in: no events and no variable arguments.
753  if (NumArgs == 4) {
754  // check that the last argument is the right block type.
755  if (!isBlockPointer(Arg3)) {
756  S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
757  << TheCall->getDirectCallee() << "block";
758  return true;
759  }
760  // we have a block type, check the prototype
761  const BlockPointerType *BPT =
762  cast<BlockPointerType>(Arg3->getType().getCanonicalType());
763  if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
764  S.Diag(Arg3->getBeginLoc(),
765  diag::err_opencl_enqueue_kernel_blocks_no_args);
766  return true;
767  }
768  return false;
769  }
770  // we can have block + varargs.
771  if (isBlockPointer(Arg3))
772  return (checkOpenCLBlockArgs(S, Arg3) ||
773  checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
774  // last two cases with either exactly 7 args or 7 args and varargs.
775  if (NumArgs >= 7) {
776  // check common block argument.
777  Expr *Arg6 = TheCall->getArg(6);
778  if (!isBlockPointer(Arg6)) {
779  S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
780  << TheCall->getDirectCallee() << "block";
781  return true;
782  }
783  if (checkOpenCLBlockArgs(S, Arg6))
784  return true;
785 
786  // Forth argument has to be any integer type.
787  if (!Arg3->getType()->isIntegerType()) {
788  S.Diag(TheCall->getArg(3)->getBeginLoc(),
789  diag::err_opencl_builtin_expected_type)
790  << TheCall->getDirectCallee() << "integer";
791  return true;
792  }
793  // check remaining common arguments.
794  Expr *Arg4 = TheCall->getArg(4);
795  Expr *Arg5 = TheCall->getArg(5);
796 
797  // Fifth argument is always passed as a pointer to clk_event_t.
798  if (!Arg4->isNullPointerConstant(S.Context,
801  S.Diag(TheCall->getArg(4)->getBeginLoc(),
802  diag::err_opencl_builtin_expected_type)
803  << TheCall->getDirectCallee()
805  return true;
806  }
807 
808  // Sixth argument is always passed as a pointer to clk_event_t.
809  if (!Arg5->isNullPointerConstant(S.Context,
811  !(Arg5->getType()->isPointerType() &&
812  Arg5->getType()->getPointeeType()->isClkEventT())) {
813  S.Diag(TheCall->getArg(5)->getBeginLoc(),
814  diag::err_opencl_builtin_expected_type)
815  << TheCall->getDirectCallee()
817  return true;
818  }
819 
820  if (NumArgs == 7)
821  return false;
822 
823  return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
824  }
825 
826  // None of the specific case has been detected, give generic error
827  S.Diag(TheCall->getBeginLoc(),
828  diag::err_opencl_enqueue_kernel_incorrect_args);
829  return true;
830 }
831 
832 /// Returns OpenCL access qual.
833 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
834  return D->getAttr<OpenCLAccessAttr>();
835 }
836 
837 /// Returns true if pipe element type is different from the pointer.
838 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
839  const Expr *Arg0 = Call->getArg(0);
840  // First argument type should always be pipe.
841  if (!Arg0->getType()->isPipeType()) {
842  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
843  << Call->getDirectCallee() << Arg0->getSourceRange();
844  return true;
845  }
846  OpenCLAccessAttr *AccessQual =
847  getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
848  // Validates the access qualifier is compatible with the call.
849  // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
850  // read_only and write_only, and assumed to be read_only if no qualifier is
851  // specified.
852  switch (Call->getDirectCallee()->getBuiltinID()) {
853  case Builtin::BIread_pipe:
854  case Builtin::BIreserve_read_pipe:
855  case Builtin::BIcommit_read_pipe:
856  case Builtin::BIwork_group_reserve_read_pipe:
857  case Builtin::BIsub_group_reserve_read_pipe:
858  case Builtin::BIwork_group_commit_read_pipe:
859  case Builtin::BIsub_group_commit_read_pipe:
860  if (!(!AccessQual || AccessQual->isReadOnly())) {
861  S.Diag(Arg0->getBeginLoc(),
862  diag::err_opencl_builtin_pipe_invalid_access_modifier)
863  << "read_only" << Arg0->getSourceRange();
864  return true;
865  }
866  break;
867  case Builtin::BIwrite_pipe:
868  case Builtin::BIreserve_write_pipe:
869  case Builtin::BIcommit_write_pipe:
870  case Builtin::BIwork_group_reserve_write_pipe:
871  case Builtin::BIsub_group_reserve_write_pipe:
872  case Builtin::BIwork_group_commit_write_pipe:
873  case Builtin::BIsub_group_commit_write_pipe:
874  if (!(AccessQual && AccessQual->isWriteOnly())) {
875  S.Diag(Arg0->getBeginLoc(),
876  diag::err_opencl_builtin_pipe_invalid_access_modifier)
877  << "write_only" << Arg0->getSourceRange();
878  return true;
879  }
880  break;
881  default:
882  break;
883  }
884  return false;
885 }
886 
887 /// Returns true if pipe element type is different from the pointer.
888 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
889  const Expr *Arg0 = Call->getArg(0);
890  const Expr *ArgIdx = Call->getArg(Idx);
891  const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
892  const QualType EltTy = PipeTy->getElementType();
893  const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
894  // The Idx argument should be a pointer and the type of the pointer and
895  // the type of pipe element should also be the same.
896  if (!ArgTy ||
897  !S.Context.hasSameType(
898  EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
899  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
900  << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
901  << ArgIdx->getType() << ArgIdx->getSourceRange();
902  return true;
903  }
904  return false;
905 }
906 
907 // Performs semantic analysis for the read/write_pipe call.
908 // \param S Reference to the semantic analyzer.
909 // \param Call A pointer to the builtin call.
910 // \return True if a semantic error has been found, false otherwise.
911 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
912  // OpenCL v2.0 s6.13.16.2 - The built-in read/write
913  // functions have two forms.
914  switch (Call->getNumArgs()) {
915  case 2:
916  if (checkOpenCLPipeArg(S, Call))
917  return true;
918  // The call with 2 arguments should be
919  // read/write_pipe(pipe T, T*).
920  // Check packet type T.
921  if (checkOpenCLPipePacketType(S, Call, 1))
922  return true;
923  break;
924 
925  case 4: {
926  if (checkOpenCLPipeArg(S, Call))
927  return true;
928  // The call with 4 arguments should be
929  // read/write_pipe(pipe T, reserve_id_t, uint, T*).
930  // Check reserve_id_t.
931  if (!Call->getArg(1)->getType()->isReserveIDT()) {
932  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
933  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
934  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
935  return true;
936  }
937 
938  // Check the index.
939  const Expr *Arg2 = Call->getArg(2);
940  if (!Arg2->getType()->isIntegerType() &&
941  !Arg2->getType()->isUnsignedIntegerType()) {
942  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
943  << Call->getDirectCallee() << S.Context.UnsignedIntTy
944  << Arg2->getType() << Arg2->getSourceRange();
945  return true;
946  }
947 
948  // Check packet type T.
949  if (checkOpenCLPipePacketType(S, Call, 3))
950  return true;
951  } break;
952  default:
953  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
954  << Call->getDirectCallee() << Call->getSourceRange();
955  return true;
956  }
957 
958  return false;
959 }
960 
961 // Performs a semantic analysis on the {work_group_/sub_group_
962 // /_}reserve_{read/write}_pipe
963 // \param S Reference to the semantic analyzer.
964 // \param Call The call to the builtin function to be analyzed.
965 // \return True if a semantic error was found, false otherwise.
966 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
967  if (checkArgCount(S, Call, 2))
968  return true;
969 
970  if (checkOpenCLPipeArg(S, Call))
971  return true;
972 
973  // Check the reserve size.
974  if (!Call->getArg(1)->getType()->isIntegerType() &&
975  !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
976  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
977  << Call->getDirectCallee() << S.Context.UnsignedIntTy
978  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
979  return true;
980  }
981 
982  // Since return type of reserve_read/write_pipe built-in function is
983  // reserve_id_t, which is not defined in the builtin def file , we used int
984  // as return type and need to override the return type of these functions.
985  Call->setType(S.Context.OCLReserveIDTy);
986 
987  return false;
988 }
989 
990 // Performs a semantic analysis on {work_group_/sub_group_
991 // /_}commit_{read/write}_pipe
992 // \param S Reference to the semantic analyzer.
993 // \param Call The call to the builtin function to be analyzed.
994 // \return True if a semantic error was found, false otherwise.
995 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
996  if (checkArgCount(S, Call, 2))
997  return true;
998 
999  if (checkOpenCLPipeArg(S, Call))
1000  return true;
1001 
1002  // Check reserve_id_t.
1003  if (!Call->getArg(1)->getType()->isReserveIDT()) {
1004  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1005  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1006  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1007  return true;
1008  }
1009 
1010  return false;
1011 }
1012 
1013 // Performs a semantic analysis on the call to built-in Pipe
1014 // Query Functions.
1015 // \param S Reference to the semantic analyzer.
1016 // \param Call The call to the builtin function to be analyzed.
1017 // \return True if a semantic error was found, false otherwise.
1018 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1019  if (checkArgCount(S, Call, 1))
1020  return true;
1021 
1022  if (!Call->getArg(0)->getType()->isPipeType()) {
1023  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1024  << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1025  return true;
1026  }
1027 
1028  return false;
1029 }
1030 
1031 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1032 // Performs semantic analysis for the to_global/local/private call.
1033 // \param S Reference to the semantic analyzer.
1034 // \param BuiltinID ID of the builtin function.
1035 // \param Call A pointer to the builtin call.
1036 // \return True if a semantic error has been found, false otherwise.
1037 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1038  CallExpr *Call) {
1039  if (Call->getNumArgs() != 1) {
1040  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
1041  << Call->getDirectCallee() << Call->getSourceRange();
1042  return true;
1043  }
1044 
1045  auto RT = Call->getArg(0)->getType();
1046  if (!RT->isPointerType() || RT->getPointeeType()
1047  .getAddressSpace() == LangAS::opencl_constant) {
1048  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1049  << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1050  return true;
1051  }
1052 
1053  if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1054  S.Diag(Call->getArg(0)->getBeginLoc(),
1055  diag::warn_opencl_generic_address_space_arg)
1056  << Call->getDirectCallee()->getNameInfo().getAsString()
1057  << Call->getArg(0)->getSourceRange();
1058  }
1059 
1060  RT = RT->getPointeeType();
1061  auto Qual = RT.getQualifiers();
1062  switch (BuiltinID) {
1063  case Builtin::BIto_global:
1064  Qual.setAddressSpace(LangAS::opencl_global);
1065  break;
1066  case Builtin::BIto_local:
1067  Qual.setAddressSpace(LangAS::opencl_local);
1068  break;
1069  case Builtin::BIto_private:
1070  Qual.setAddressSpace(LangAS::opencl_private);
1071  break;
1072  default:
1073  llvm_unreachable("Invalid builtin function");
1074  }
1076  RT.getUnqualifiedType(), Qual)));
1077 
1078  return false;
1079 }
1080 
1082  if (checkArgCount(S, TheCall, 1))
1083  return ExprError();
1084 
1085  // Compute __builtin_launder's parameter type from the argument.
1086  // The parameter type is:
1087  // * The type of the argument if it's not an array or function type,
1088  // Otherwise,
1089  // * The decayed argument type.
1090  QualType ParamTy = [&]() {
1091  QualType ArgTy = TheCall->getArg(0)->getType();
1092  if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1093  return S.Context.getPointerType(Ty->getElementType());
1094  if (ArgTy->isFunctionType()) {
1095  return S.Context.getPointerType(ArgTy);
1096  }
1097  return ArgTy;
1098  }();
1099 
1100  TheCall->setType(ParamTy);
1101 
1102  auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1103  if (!ParamTy->isPointerType())
1104  return 0;
1105  if (ParamTy->isFunctionPointerType())
1106  return 1;
1107  if (ParamTy->isVoidPointerType())
1108  return 2;
1109  return llvm::Optional<unsigned>{};
1110  }();
1111  if (DiagSelect.hasValue()) {
1112  S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1113  << DiagSelect.getValue() << TheCall->getSourceRange();
1114  return ExprError();
1115  }
1116 
1117  // We either have an incomplete class type, or we have a class template
1118  // whose instantiation has not been forced. Example:
1119  //
1120  // template <class T> struct Foo { T value; };
1121  // Foo<int> *p = nullptr;
1122  // auto *d = __builtin_launder(p);
1123  if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1124  diag::err_incomplete_type))
1125  return ExprError();
1126 
1127  assert(ParamTy->getPointeeType()->isObjectType() &&
1128  "Unhandled non-object pointer case");
1129 
1130  InitializedEntity Entity =
1132  ExprResult Arg =
1133  S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1134  if (Arg.isInvalid())
1135  return ExprError();
1136  TheCall->setArg(0, Arg.get());
1137 
1138  return TheCall;
1139 }
1140 
1141 // Emit an error and return true if the current architecture is not in the list
1142 // of supported architectures.
1143 static bool
1144 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1145  ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1146  llvm::Triple::ArchType CurArch =
1147  S.getASTContext().getTargetInfo().getTriple().getArch();
1148  if (llvm::is_contained(SupportedArchs, CurArch))
1149  return false;
1150  S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1151  << TheCall->getSourceRange();
1152  return true;
1153 }
1154 
1155 ExprResult
1156 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1157  CallExpr *TheCall) {
1158  ExprResult TheCallResult(TheCall);
1159 
1160  // Find out if any arguments are required to be integer constant expressions.
1161  unsigned ICEArguments = 0;
1163  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1164  if (Error != ASTContext::GE_None)
1165  ICEArguments = 0; // Don't diagnose previously diagnosed errors.
1166 
1167  // If any arguments are required to be ICE's, check and diagnose.
1168  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1169  // Skip arguments not required to be ICE's.
1170  if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1171 
1172  llvm::APSInt Result;
1173  if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1174  return true;
1175  ICEArguments &= ~(1 << ArgNo);
1176  }
1177 
1178  switch (BuiltinID) {
1179  case Builtin::BI__builtin___CFStringMakeConstantString:
1180  assert(TheCall->getNumArgs() == 1 &&
1181  "Wrong # arguments to builtin CFStringMakeConstantString");
1182  if (CheckObjCString(TheCall->getArg(0)))
1183  return ExprError();
1184  break;
1185  case Builtin::BI__builtin_ms_va_start:
1186  case Builtin::BI__builtin_stdarg_start:
1187  case Builtin::BI__builtin_va_start:
1188  if (SemaBuiltinVAStart(BuiltinID, TheCall))
1189  return ExprError();
1190  break;
1191  case Builtin::BI__va_start: {
1192  switch (Context.getTargetInfo().getTriple().getArch()) {
1193  case llvm::Triple::aarch64:
1194  case llvm::Triple::arm:
1195  case llvm::Triple::thumb:
1196  if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1197  return ExprError();
1198  break;
1199  default:
1200  if (SemaBuiltinVAStart(BuiltinID, TheCall))
1201  return ExprError();
1202  break;
1203  }
1204  break;
1205  }
1206 
1207  // The acquire, release, and no fence variants are ARM and AArch64 only.
1208  case Builtin::BI_interlockedbittestandset_acq:
1209  case Builtin::BI_interlockedbittestandset_rel:
1210  case Builtin::BI_interlockedbittestandset_nf:
1211  case Builtin::BI_interlockedbittestandreset_acq:
1212  case Builtin::BI_interlockedbittestandreset_rel:
1213  case Builtin::BI_interlockedbittestandreset_nf:
1215  *this, BuiltinID, TheCall,
1216  {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1217  return ExprError();
1218  break;
1219 
1220  // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1221  case Builtin::BI_bittest64:
1222  case Builtin::BI_bittestandcomplement64:
1223  case Builtin::BI_bittestandreset64:
1224  case Builtin::BI_bittestandset64:
1225  case Builtin::BI_interlockedbittestandreset64:
1226  case Builtin::BI_interlockedbittestandset64:
1227  if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1228  {llvm::Triple::x86_64, llvm::Triple::arm,
1229  llvm::Triple::thumb, llvm::Triple::aarch64}))
1230  return ExprError();
1231  break;
1232 
1233  case Builtin::BI__builtin_isgreater:
1234  case Builtin::BI__builtin_isgreaterequal:
1235  case Builtin::BI__builtin_isless:
1236  case Builtin::BI__builtin_islessequal:
1237  case Builtin::BI__builtin_islessgreater:
1238  case Builtin::BI__builtin_isunordered:
1239  if (SemaBuiltinUnorderedCompare(TheCall))
1240  return ExprError();
1241  break;
1242  case Builtin::BI__builtin_fpclassify:
1243  if (SemaBuiltinFPClassification(TheCall, 6))
1244  return ExprError();
1245  break;
1246  case Builtin::BI__builtin_isfinite:
1247  case Builtin::BI__builtin_isinf:
1248  case Builtin::BI__builtin_isinf_sign:
1249  case Builtin::BI__builtin_isnan:
1250  case Builtin::BI__builtin_isnormal:
1251  case Builtin::BI__builtin_signbit:
1252  case Builtin::BI__builtin_signbitf:
1253  case Builtin::BI__builtin_signbitl:
1254  if (SemaBuiltinFPClassification(TheCall, 1))
1255  return ExprError();
1256  break;
1257  case Builtin::BI__builtin_shufflevector:
1258  return SemaBuiltinShuffleVector(TheCall);
1259  // TheCall will be freed by the smart pointer here, but that's fine, since
1260  // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1261  case Builtin::BI__builtin_prefetch:
1262  if (SemaBuiltinPrefetch(TheCall))
1263  return ExprError();
1264  break;
1265  case Builtin::BI__builtin_alloca_with_align:
1266  if (SemaBuiltinAllocaWithAlign(TheCall))
1267  return ExprError();
1268  LLVM_FALLTHROUGH;
1269  case Builtin::BI__builtin_alloca:
1270  Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1271  << TheCall->getDirectCallee();
1272  break;
1273  case Builtin::BI__assume:
1274  case Builtin::BI__builtin_assume:
1275  if (SemaBuiltinAssume(TheCall))
1276  return ExprError();
1277  break;
1278  case Builtin::BI__builtin_assume_aligned:
1279  if (SemaBuiltinAssumeAligned(TheCall))
1280  return ExprError();
1281  break;
1282  case Builtin::BI__builtin_dynamic_object_size:
1283  case Builtin::BI__builtin_object_size:
1284  if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1285  return ExprError();
1286  break;
1287  case Builtin::BI__builtin_longjmp:
1288  if (SemaBuiltinLongjmp(TheCall))
1289  return ExprError();
1290  break;
1291  case Builtin::BI__builtin_setjmp:
1292  if (SemaBuiltinSetjmp(TheCall))
1293  return ExprError();
1294  break;
1295  case Builtin::BI_setjmp:
1296  case Builtin::BI_setjmpex:
1297  if (checkArgCount(*this, TheCall, 1))
1298  return true;
1299  break;
1300  case Builtin::BI__builtin_classify_type:
1301  if (checkArgCount(*this, TheCall, 1)) return true;
1302  TheCall->setType(Context.IntTy);
1303  break;
1304  case Builtin::BI__builtin_constant_p: {
1305  if (checkArgCount(*this, TheCall, 1)) return true;
1306  ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1307  if (Arg.isInvalid()) return true;
1308  TheCall->setArg(0, Arg.get());
1309  TheCall->setType(Context.IntTy);
1310  break;
1311  }
1312  case Builtin::BI__builtin_launder:
1313  return SemaBuiltinLaunder(*this, TheCall);
1314  case Builtin::BI__sync_fetch_and_add:
1315  case Builtin::BI__sync_fetch_and_add_1:
1316  case Builtin::BI__sync_fetch_and_add_2:
1317  case Builtin::BI__sync_fetch_and_add_4:
1318  case Builtin::BI__sync_fetch_and_add_8:
1319  case Builtin::BI__sync_fetch_and_add_16:
1320  case Builtin::BI__sync_fetch_and_sub:
1321  case Builtin::BI__sync_fetch_and_sub_1:
1322  case Builtin::BI__sync_fetch_and_sub_2:
1323  case Builtin::BI__sync_fetch_and_sub_4:
1324  case Builtin::BI__sync_fetch_and_sub_8:
1325  case Builtin::BI__sync_fetch_and_sub_16:
1326  case Builtin::BI__sync_fetch_and_or:
1327  case Builtin::BI__sync_fetch_and_or_1:
1328  case Builtin::BI__sync_fetch_and_or_2:
1329  case Builtin::BI__sync_fetch_and_or_4:
1330  case Builtin::BI__sync_fetch_and_or_8:
1331  case Builtin::BI__sync_fetch_and_or_16:
1332  case Builtin::BI__sync_fetch_and_and:
1333  case Builtin::BI__sync_fetch_and_and_1:
1334  case Builtin::BI__sync_fetch_and_and_2:
1335  case Builtin::BI__sync_fetch_and_and_4:
1336  case Builtin::BI__sync_fetch_and_and_8:
1337  case Builtin::BI__sync_fetch_and_and_16:
1338  case Builtin::BI__sync_fetch_and_xor:
1339  case Builtin::BI__sync_fetch_and_xor_1:
1340  case Builtin::BI__sync_fetch_and_xor_2:
1341  case Builtin::BI__sync_fetch_and_xor_4:
1342  case Builtin::BI__sync_fetch_and_xor_8:
1343  case Builtin::BI__sync_fetch_and_xor_16:
1344  case Builtin::BI__sync_fetch_and_nand:
1345  case Builtin::BI__sync_fetch_and_nand_1:
1346  case Builtin::BI__sync_fetch_and_nand_2:
1347  case Builtin::BI__sync_fetch_and_nand_4:
1348  case Builtin::BI__sync_fetch_and_nand_8:
1349  case Builtin::BI__sync_fetch_and_nand_16:
1350  case Builtin::BI__sync_add_and_fetch:
1351  case Builtin::BI__sync_add_and_fetch_1:
1352  case Builtin::BI__sync_add_and_fetch_2:
1353  case Builtin::BI__sync_add_and_fetch_4:
1354  case Builtin::BI__sync_add_and_fetch_8:
1355  case Builtin::BI__sync_add_and_fetch_16:
1356  case Builtin::BI__sync_sub_and_fetch:
1357  case Builtin::BI__sync_sub_and_fetch_1:
1358  case Builtin::BI__sync_sub_and_fetch_2:
1359  case Builtin::BI__sync_sub_and_fetch_4:
1360  case Builtin::BI__sync_sub_and_fetch_8:
1361  case Builtin::BI__sync_sub_and_fetch_16:
1362  case Builtin::BI__sync_and_and_fetch:
1363  case Builtin::BI__sync_and_and_fetch_1:
1364  case Builtin::BI__sync_and_and_fetch_2:
1365  case Builtin::BI__sync_and_and_fetch_4:
1366  case Builtin::BI__sync_and_and_fetch_8:
1367  case Builtin::BI__sync_and_and_fetch_16:
1368  case Builtin::BI__sync_or_and_fetch:
1369  case Builtin::BI__sync_or_and_fetch_1:
1370  case Builtin::BI__sync_or_and_fetch_2:
1371  case Builtin::BI__sync_or_and_fetch_4:
1372  case Builtin::BI__sync_or_and_fetch_8:
1373  case Builtin::BI__sync_or_and_fetch_16:
1374  case Builtin::BI__sync_xor_and_fetch:
1375  case Builtin::BI__sync_xor_and_fetch_1:
1376  case Builtin::BI__sync_xor_and_fetch_2:
1377  case Builtin::BI__sync_xor_and_fetch_4:
1378  case Builtin::BI__sync_xor_and_fetch_8:
1379  case Builtin::BI__sync_xor_and_fetch_16:
1380  case Builtin::BI__sync_nand_and_fetch:
1381  case Builtin::BI__sync_nand_and_fetch_1:
1382  case Builtin::BI__sync_nand_and_fetch_2:
1383  case Builtin::BI__sync_nand_and_fetch_4:
1384  case Builtin::BI__sync_nand_and_fetch_8:
1385  case Builtin::BI__sync_nand_and_fetch_16:
1386  case Builtin::BI__sync_val_compare_and_swap:
1387  case Builtin::BI__sync_val_compare_and_swap_1:
1388  case Builtin::BI__sync_val_compare_and_swap_2:
1389  case Builtin::BI__sync_val_compare_and_swap_4:
1390  case Builtin::BI__sync_val_compare_and_swap_8:
1391  case Builtin::BI__sync_val_compare_and_swap_16:
1392  case Builtin::BI__sync_bool_compare_and_swap:
1393  case Builtin::BI__sync_bool_compare_and_swap_1:
1394  case Builtin::BI__sync_bool_compare_and_swap_2:
1395  case Builtin::BI__sync_bool_compare_and_swap_4:
1396  case Builtin::BI__sync_bool_compare_and_swap_8:
1397  case Builtin::BI__sync_bool_compare_and_swap_16:
1398  case Builtin::BI__sync_lock_test_and_set:
1399  case Builtin::BI__sync_lock_test_and_set_1:
1400  case Builtin::BI__sync_lock_test_and_set_2:
1401  case Builtin::BI__sync_lock_test_and_set_4:
1402  case Builtin::BI__sync_lock_test_and_set_8:
1403  case Builtin::BI__sync_lock_test_and_set_16:
1404  case Builtin::BI__sync_lock_release:
1405  case Builtin::BI__sync_lock_release_1:
1406  case Builtin::BI__sync_lock_release_2:
1407  case Builtin::BI__sync_lock_release_4:
1408  case Builtin::BI__sync_lock_release_8:
1409  case Builtin::BI__sync_lock_release_16:
1410  case Builtin::BI__sync_swap:
1411  case Builtin::BI__sync_swap_1:
1412  case Builtin::BI__sync_swap_2:
1413  case Builtin::BI__sync_swap_4:
1414  case Builtin::BI__sync_swap_8:
1415  case Builtin::BI__sync_swap_16:
1416  return SemaBuiltinAtomicOverloaded(TheCallResult);
1417  case Builtin::BI__sync_synchronize:
1418  Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1419  << TheCall->getCallee()->getSourceRange();
1420  break;
1421  case Builtin::BI__builtin_nontemporal_load:
1422  case Builtin::BI__builtin_nontemporal_store:
1423  return SemaBuiltinNontemporalOverloaded(TheCallResult);
1424 #define BUILTIN(ID, TYPE, ATTRS)
1425 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1426  case Builtin::BI##ID: \
1427  return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1428 #include "clang/Basic/Builtins.def"
1429  case Builtin::BI__annotation:
1430  if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1431  return ExprError();
1432  break;
1433  case Builtin::BI__builtin_annotation:
1434  if (SemaBuiltinAnnotation(*this, TheCall))
1435  return ExprError();
1436  break;
1437  case Builtin::BI__builtin_addressof:
1438  if (SemaBuiltinAddressof(*this, TheCall))
1439  return ExprError();
1440  break;
1441  case Builtin::BI__builtin_is_aligned:
1442  case Builtin::BI__builtin_align_up:
1443  case Builtin::BI__builtin_align_down:
1444  if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1445  return ExprError();
1446  break;
1447  case Builtin::BI__builtin_add_overflow:
1448  case Builtin::BI__builtin_sub_overflow:
1449  case Builtin::BI__builtin_mul_overflow:
1450  if (SemaBuiltinOverflow(*this, TheCall))
1451  return ExprError();
1452  break;
1453  case Builtin::BI__builtin_operator_new:
1454  case Builtin::BI__builtin_operator_delete: {
1455  bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1456  ExprResult Res =
1457  SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1458  if (Res.isInvalid())
1459  CorrectDelayedTyposInExpr(TheCallResult.get());
1460  return Res;
1461  }
1462  case Builtin::BI__builtin_dump_struct: {
1463  // We first want to ensure we are called with 2 arguments
1464  if (checkArgCount(*this, TheCall, 2))
1465  return ExprError();
1466  // Ensure that the first argument is of type 'struct XX *'
1467  const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1468  const QualType PtrArgType = PtrArg->getType();
1469  if (!PtrArgType->isPointerType() ||
1470  !PtrArgType->getPointeeType()->isRecordType()) {
1471  Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1472  << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1473  << "structure pointer";
1474  return ExprError();
1475  }
1476 
1477  // Ensure that the second argument is of type 'FunctionType'
1478  const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1479  const QualType FnPtrArgType = FnPtrArg->getType();
1480  if (!FnPtrArgType->isPointerType()) {
1481  Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1482  << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1483  << FnPtrArgType << "'int (*)(const char *, ...)'";
1484  return ExprError();
1485  }
1486 
1487  const auto *FuncType =
1488  FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1489 
1490  if (!FuncType) {
1491  Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1492  << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1493  << FnPtrArgType << "'int (*)(const char *, ...)'";
1494  return ExprError();
1495  }
1496 
1497  if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1498  if (!FT->getNumParams()) {
1499  Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1500  << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1501  << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1502  return ExprError();
1503  }
1504  QualType PT = FT->getParamType(0);
1505  if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1506  !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1507  !PT->getPointeeType().isConstQualified()) {
1508  Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1509  << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1510  << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1511  return ExprError();
1512  }
1513  }
1514 
1515  TheCall->setType(Context.IntTy);
1516  break;
1517  }
1518  case Builtin::BI__builtin_preserve_access_index:
1519  if (SemaBuiltinPreserveAI(*this, TheCall))
1520  return ExprError();
1521  break;
1522  case Builtin::BI__builtin_call_with_static_chain:
1523  if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1524  return ExprError();
1525  break;
1526  case Builtin::BI__exception_code:
1527  case Builtin::BI_exception_code:
1528  if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1529  diag::err_seh___except_block))
1530  return ExprError();
1531  break;
1532  case Builtin::BI__exception_info:
1533  case Builtin::BI_exception_info:
1534  if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1535  diag::err_seh___except_filter))
1536  return ExprError();
1537  break;
1538  case Builtin::BI__GetExceptionInfo:
1539  if (checkArgCount(*this, TheCall, 1))
1540  return ExprError();
1541 
1542  if (CheckCXXThrowOperand(
1543  TheCall->getBeginLoc(),
1544  Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1545  TheCall))
1546  return ExprError();
1547 
1548  TheCall->setType(Context.VoidPtrTy);
1549  break;
1550  // OpenCL v2.0, s6.13.16 - Pipe functions
1551  case Builtin::BIread_pipe:
1552  case Builtin::BIwrite_pipe:
1553  // Since those two functions are declared with var args, we need a semantic
1554  // check for the argument.
1555  if (SemaBuiltinRWPipe(*this, TheCall))
1556  return ExprError();
1557  break;
1558  case Builtin::BIreserve_read_pipe:
1559  case Builtin::BIreserve_write_pipe:
1560  case Builtin::BIwork_group_reserve_read_pipe:
1561  case Builtin::BIwork_group_reserve_write_pipe:
1562  if (SemaBuiltinReserveRWPipe(*this, TheCall))
1563  return ExprError();
1564  break;
1565  case Builtin::BIsub_group_reserve_read_pipe:
1566  case Builtin::BIsub_group_reserve_write_pipe:
1567  if (checkOpenCLSubgroupExt(*this, TheCall) ||
1568  SemaBuiltinReserveRWPipe(*this, TheCall))
1569  return ExprError();
1570  break;
1571  case Builtin::BIcommit_read_pipe:
1572  case Builtin::BIcommit_write_pipe:
1573  case Builtin::BIwork_group_commit_read_pipe:
1574  case Builtin::BIwork_group_commit_write_pipe:
1575  if (SemaBuiltinCommitRWPipe(*this, TheCall))
1576  return ExprError();
1577  break;
1578  case Builtin::BIsub_group_commit_read_pipe:
1579  case Builtin::BIsub_group_commit_write_pipe:
1580  if (checkOpenCLSubgroupExt(*this, TheCall) ||
1581  SemaBuiltinCommitRWPipe(*this, TheCall))
1582  return ExprError();
1583  break;
1584  case Builtin::BIget_pipe_num_packets:
1585  case Builtin::BIget_pipe_max_packets:
1586  if (SemaBuiltinPipePackets(*this, TheCall))
1587  return ExprError();
1588  break;
1589  case Builtin::BIto_global:
1590  case Builtin::BIto_local:
1591  case Builtin::BIto_private:
1592  if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1593  return ExprError();
1594  break;
1595  // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1596  case Builtin::BIenqueue_kernel:
1597  if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1598  return ExprError();
1599  break;
1600  case Builtin::BIget_kernel_work_group_size:
1601  case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1602  if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1603  return ExprError();
1604  break;
1605  case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1606  case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1607  if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1608  return ExprError();
1609  break;
1610  case Builtin::BI__builtin_os_log_format:
1611  case Builtin::BI__builtin_os_log_format_buffer_size:
1612  if (SemaBuiltinOSLogFormat(TheCall))
1613  return ExprError();
1614  break;
1615  }
1616 
1617  // Since the target specific builtins for each arch overlap, only check those
1618  // of the arch we are compiling for.
1619  if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1620  switch (Context.getTargetInfo().getTriple().getArch()) {
1621  case llvm::Triple::arm:
1622  case llvm::Triple::armeb:
1623  case llvm::Triple::thumb:
1624  case llvm::Triple::thumbeb:
1625  if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1626  return ExprError();
1627  break;
1628  case llvm::Triple::aarch64:
1629  case llvm::Triple::aarch64_32:
1630  case llvm::Triple::aarch64_be:
1631  if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1632  return ExprError();
1633  break;
1634  case llvm::Triple::bpfeb:
1635  case llvm::Triple::bpfel:
1636  if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1637  return ExprError();
1638  break;
1639  case llvm::Triple::hexagon:
1640  if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1641  return ExprError();
1642  break;
1643  case llvm::Triple::mips:
1644  case llvm::Triple::mipsel:
1645  case llvm::Triple::mips64:
1646  case llvm::Triple::mips64el:
1647  if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1648  return ExprError();
1649  break;
1650  case llvm::Triple::systemz:
1651  if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1652  return ExprError();
1653  break;
1654  case llvm::Triple::x86:
1655  case llvm::Triple::x86_64:
1656  if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1657  return ExprError();
1658  break;
1659  case llvm::Triple::ppc:
1660  case llvm::Triple::ppc64:
1661  case llvm::Triple::ppc64le:
1662  if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1663  return ExprError();
1664  break;
1665  default:
1666  break;
1667  }
1668  }
1669 
1670  return TheCallResult;
1671 }
1672 
1673 // Get the valid immediate range for the specified NEON type code.
1674 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1675  NeonTypeFlags Type(t);
1676  int IsQuad = ForceQuad ? true : Type.isQuad();
1677  switch (Type.getEltType()) {
1678  case NeonTypeFlags::Int8:
1679  case NeonTypeFlags::Poly8:
1680  return shift ? 7 : (8 << IsQuad) - 1;
1681  case NeonTypeFlags::Int16:
1682  case NeonTypeFlags::Poly16:
1683  return shift ? 15 : (4 << IsQuad) - 1;
1684  case NeonTypeFlags::Int32:
1685  return shift ? 31 : (2 << IsQuad) - 1;
1686  case NeonTypeFlags::Int64:
1687  case NeonTypeFlags::Poly64:
1688  return shift ? 63 : (1 << IsQuad) - 1;
1690  return shift ? 127 : (1 << IsQuad) - 1;
1692  assert(!shift && "cannot shift float types!");
1693  return (4 << IsQuad) - 1;
1695  assert(!shift && "cannot shift float types!");
1696  return (2 << IsQuad) - 1;
1698  assert(!shift && "cannot shift float types!");
1699  return (1 << IsQuad) - 1;
1700  }
1701  llvm_unreachable("Invalid NeonTypeFlag!");
1702 }
1703 
1704 /// getNeonEltType - Return the QualType corresponding to the elements of
1705 /// the vector type specified by the NeonTypeFlags. This is used to check
1706 /// the pointer arguments for Neon load/store intrinsics.
1708  bool IsPolyUnsigned, bool IsInt64Long) {
1709  switch (Flags.getEltType()) {
1710  case NeonTypeFlags::Int8:
1711  return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1712  case NeonTypeFlags::Int16:
1713  return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1714  case NeonTypeFlags::Int32:
1715  return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1716  case NeonTypeFlags::Int64:
1717  if (IsInt64Long)
1718  return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1719  else
1720  return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1721  : Context.LongLongTy;
1722  case NeonTypeFlags::Poly8:
1723  return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1724  case NeonTypeFlags::Poly16:
1725  return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1726  case NeonTypeFlags::Poly64:
1727  if (IsInt64Long)
1728  return Context.UnsignedLongTy;
1729  else
1730  return Context.UnsignedLongLongTy;
1732  break;
1734  return Context.HalfTy;
1736  return Context.FloatTy;
1738  return Context.DoubleTy;
1739  }
1740  llvm_unreachable("Invalid NeonTypeFlag!");
1741 }
1742 
1743 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1744  llvm::APSInt Result;
1745  uint64_t mask = 0;
1746  unsigned TV = 0;
1747  int PtrArgNum = -1;
1748  bool HasConstPtr = false;
1749  switch (BuiltinID) {
1750 #define GET_NEON_OVERLOAD_CHECK
1751 #include "clang/Basic/arm_neon.inc"
1752 #include "clang/Basic/arm_fp16.inc"
1753 #undef GET_NEON_OVERLOAD_CHECK
1754  }
1755 
1756  // For NEON intrinsics which are overloaded on vector element type, validate
1757  // the immediate which specifies which variant to emit.
1758  unsigned ImmArg = TheCall->getNumArgs()-1;
1759  if (mask) {
1760  if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1761  return true;
1762 
1763  TV = Result.getLimitedValue(64);
1764  if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1765  return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1766  << TheCall->getArg(ImmArg)->getSourceRange();
1767  }
1768 
1769  if (PtrArgNum >= 0) {
1770  // Check that pointer arguments have the specified type.
1771  Expr *Arg = TheCall->getArg(PtrArgNum);
1772  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1773  Arg = ICE->getSubExpr();
1774  ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1775  QualType RHSTy = RHS.get()->getType();
1776 
1777  llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1778  bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1779  Arch == llvm::Triple::aarch64_32 ||
1780  Arch == llvm::Triple::aarch64_be;
1781  bool IsInt64Long =
1783  QualType EltTy =
1784  getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1785  if (HasConstPtr)
1786  EltTy = EltTy.withConst();
1787  QualType LHSTy = Context.getPointerType(EltTy);
1788  AssignConvertType ConvTy;
1789  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1790  if (RHS.isInvalid())
1791  return true;
1792  if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1793  RHS.get(), AA_Assigning))
1794  return true;
1795  }
1796 
1797  // For NEON intrinsics which take an immediate value as part of the
1798  // instruction, range check them here.
1799  unsigned i = 0, l = 0, u = 0;
1800  switch (BuiltinID) {
1801  default:
1802  return false;
1803  #define GET_NEON_IMMEDIATE_CHECK
1804  #include "clang/Basic/arm_neon.inc"
1805  #include "clang/Basic/arm_fp16.inc"
1806  #undef GET_NEON_IMMEDIATE_CHECK
1807  }
1808 
1809  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1810 }
1811 
1812 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1813  switch (BuiltinID) {
1814  default:
1815  return false;
1816  #include "clang/Basic/arm_mve_builtin_sema.inc"
1817  }
1818 }
1819 
1820 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1821  unsigned MaxWidth) {
1822  assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1823  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1824  BuiltinID == ARM::BI__builtin_arm_strex ||
1825  BuiltinID == ARM::BI__builtin_arm_stlex ||
1826  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1827  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1828  BuiltinID == AArch64::BI__builtin_arm_strex ||
1829  BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1830  "unexpected ARM builtin");
1831  bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1832  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1833  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1834  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1835 
1836  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1837 
1838  // Ensure that we have the proper number of arguments.
1839  if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1840  return true;
1841 
1842  // Inspect the pointer argument of the atomic builtin. This should always be
1843  // a pointer type, whose element is an integral scalar or pointer type.
1844  // Because it is a pointer type, we don't have to worry about any implicit
1845  // casts here.
1846  Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1847  ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1848  if (PointerArgRes.isInvalid())
1849  return true;
1850  PointerArg = PointerArgRes.get();
1851 
1852  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1853  if (!pointerType) {
1854  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1855  << PointerArg->getType() << PointerArg->getSourceRange();
1856  return true;
1857  }
1858 
1859  // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1860  // task is to insert the appropriate casts into the AST. First work out just
1861  // what the appropriate type is.
1862  QualType ValType = pointerType->getPointeeType();
1863  QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1864  if (IsLdrex)
1865  AddrType.addConst();
1866 
1867  // Issue a warning if the cast is dodgy.
1868  CastKind CastNeeded = CK_NoOp;
1869  if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1870  CastNeeded = CK_BitCast;
1871  Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1872  << PointerArg->getType() << Context.getPointerType(AddrType)
1873  << AA_Passing << PointerArg->getSourceRange();
1874  }
1875 
1876  // Finally, do the cast and replace the argument with the corrected version.
1877  AddrType = Context.getPointerType(AddrType);
1878  PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1879  if (PointerArgRes.isInvalid())
1880  return true;
1881  PointerArg = PointerArgRes.get();
1882 
1883  TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1884 
1885  // In general, we allow ints, floats and pointers to be loaded and stored.
1886  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1887  !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1888  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1889  << PointerArg->getType() << PointerArg->getSourceRange();
1890  return true;
1891  }
1892 
1893  // But ARM doesn't have instructions to deal with 128-bit versions.
1894  if (Context.getTypeSize(ValType) > MaxWidth) {
1895  assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1896  Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1897  << PointerArg->getType() << PointerArg->getSourceRange();
1898  return true;
1899  }
1900 
1901  switch (ValType.getObjCLifetime()) {
1902  case Qualifiers::OCL_None:
1904  // okay
1905  break;
1906 
1907  case Qualifiers::OCL_Weak:
1910  Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1911  << ValType << PointerArg->getSourceRange();
1912  return true;
1913  }
1914 
1915  if (IsLdrex) {
1916  TheCall->setType(ValType);
1917  return false;
1918  }
1919 
1920  // Initialize the argument to be stored.
1921  ExprResult ValArg = TheCall->getArg(0);
1923  Context, ValType, /*consume*/ false);
1924  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1925  if (ValArg.isInvalid())
1926  return true;
1927  TheCall->setArg(0, ValArg.get());
1928 
1929  // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1930  // but the custom checker bypasses all default analysis.
1931  TheCall->setType(Context.IntTy);
1932  return false;
1933 }
1934 
1935 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1936  if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1937  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1938  BuiltinID == ARM::BI__builtin_arm_strex ||
1939  BuiltinID == ARM::BI__builtin_arm_stlex) {
1940  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1941  }
1942 
1943  if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1944  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1945  SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1946  }
1947 
1948  if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1949  BuiltinID == ARM::BI__builtin_arm_wsr64)
1950  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1951 
1952  if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1953  BuiltinID == ARM::BI__builtin_arm_rsrp ||
1954  BuiltinID == ARM::BI__builtin_arm_wsr ||
1955  BuiltinID == ARM::BI__builtin_arm_wsrp)
1956  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1957 
1958  if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1959  return true;
1960  if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
1961  return true;
1962 
1963  // For intrinsics which take an immediate value as part of the instruction,
1964  // range check them here.
1965  // FIXME: VFP Intrinsics should error if VFP not present.
1966  switch (BuiltinID) {
1967  default: return false;
1968  case ARM::BI__builtin_arm_ssat:
1969  return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1970  case ARM::BI__builtin_arm_usat:
1971  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1972  case ARM::BI__builtin_arm_ssat16:
1973  return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1974  case ARM::BI__builtin_arm_usat16:
1975  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1976  case ARM::BI__builtin_arm_vcvtr_f:
1977  case ARM::BI__builtin_arm_vcvtr_d:
1978  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1979  case ARM::BI__builtin_arm_dmb:
1980  case ARM::BI__builtin_arm_dsb:
1981  case ARM::BI__builtin_arm_isb:
1982  case ARM::BI__builtin_arm_dbg:
1983  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1984  }
1985 }
1986 
1987 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1988  CallExpr *TheCall) {
1989  if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1990  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1991  BuiltinID == AArch64::BI__builtin_arm_strex ||
1992  BuiltinID == AArch64::BI__builtin_arm_stlex) {
1993  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1994  }
1995 
1996  if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1997  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1998  SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1999  SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2000  SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2001  }
2002 
2003  if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2004  BuiltinID == AArch64::BI__builtin_arm_wsr64)
2005  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2006 
2007  // Memory Tagging Extensions (MTE) Intrinsics
2008  if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2009  BuiltinID == AArch64::BI__builtin_arm_addg ||
2010  BuiltinID == AArch64::BI__builtin_arm_gmi ||
2011  BuiltinID == AArch64::BI__builtin_arm_ldg ||
2012  BuiltinID == AArch64::BI__builtin_arm_stg ||
2013  BuiltinID == AArch64::BI__builtin_arm_subp) {
2014  return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2015  }
2016 
2017  if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2018  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2019  BuiltinID == AArch64::BI__builtin_arm_wsr ||
2020  BuiltinID == AArch64::BI__builtin_arm_wsrp)
2021  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2022 
2023  // Only check the valid encoding range. Any constant in this range would be
2024  // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2025  // an exception for incorrect registers. This matches MSVC behavior.
2026  if (BuiltinID == AArch64::BI_ReadStatusReg ||
2027  BuiltinID == AArch64::BI_WriteStatusReg)
2028  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2029 
2030  if (BuiltinID == AArch64::BI__getReg)
2031  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2032 
2033  if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
2034  return true;
2035 
2036  // For intrinsics which take an immediate value as part of the instruction,
2037  // range check them here.
2038  unsigned i = 0, l = 0, u = 0;
2039  switch (BuiltinID) {
2040  default: return false;
2041  case AArch64::BI__builtin_arm_dmb:
2042  case AArch64::BI__builtin_arm_dsb:
2043  case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2044  case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2045  }
2046 
2047  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2048 }
2049 
2050 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2051  CallExpr *TheCall) {
2052  assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
2053  "unexpected ARM builtin");
2054 
2055  if (checkArgCount(*this, TheCall, 2))
2056  return true;
2057 
2058  // The first argument needs to be a record field access.
2059  // If it is an array element access, we delay decision
2060  // to BPF backend to check whether the access is a
2061  // field access or not.
2062  Expr *Arg = TheCall->getArg(0);
2063  if (Arg->getType()->getAsPlaceholderType() ||
2064  (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
2065  !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
2066  !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
2067  Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
2068  << 1 << Arg->getSourceRange();
2069  return true;
2070  }
2071 
2072  // The second argument needs to be a constant int
2074  if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
2075  Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
2076  << 2 << Arg->getSourceRange();
2077  return true;
2078  }
2079 
2080  TheCall->setType(Context.UnsignedIntTy);
2081  return false;
2082 }
2083 
2084 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
2085  struct BuiltinAndString {
2086  unsigned BuiltinID;
2087  const char *Str;
2088  };
2089 
2090  static BuiltinAndString ValidCPU[] = {
2091  { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
2092  { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
2093  { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
2094  { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
2095  { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
2096  { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
2097  { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
2098  { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
2099  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
2100  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
2101  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
2102  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
2103  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
2104  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
2105  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
2106  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
2107  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
2108  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
2109  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
2110  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
2111  { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
2112  { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
2113  { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
2114  };
2115 
2116  static BuiltinAndString ValidHVX[] = {
2117  { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
2118  { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
2119  { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
2120  { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
2121  { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
2122  { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
2123  { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
2124  { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
2125  { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
2126  { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
2127  { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
2128  { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
2129  { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
2130  { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
2131  { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
2132  { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
2133  { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
2134  { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
2135  { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
2136  { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
2137  { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
2138  { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
2139  { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
2140  { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
2141  { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
2142  { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
2143  { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2144  { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2145  { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2146  { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2147  { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2148  { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2149  { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2150  { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2151  { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2152  { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2153  { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2154  { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2155  { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2156  { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2157  { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2158  { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2159  { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2160  { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2161  { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2162  { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2163  { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2164  { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2165  { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2166  { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2167  { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2168  { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2169  { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2170  { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2171  { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2172  { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2173  { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2174  { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2175  { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2176  { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2177  { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2178  { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2179  { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2180  { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2181  { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2182  { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2183  { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2184  { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2185  { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2186  { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2187  { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2188  { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2189  { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2190  { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2191  { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2192  { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2193  { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2194  { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2195  { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2196  { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2197  { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2198  { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2199  { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2200  { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2201  { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2202  { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2203  { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2204  { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2205  { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2206  { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2207  { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2208  { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2209  { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2210  { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2211  { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2212  { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2213  { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2214  { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2215  { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2216  { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2217  { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2218  { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2219  { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2220  { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2221  { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2222  { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2223  { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2224  { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2225  { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2226  { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2227  { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2228  { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2229  { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2230  { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2231  { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2232  { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2233  { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2234  { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2235  { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2236  { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2237  { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2238  { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2239  { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2240  { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2241  { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2242  { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2243  { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2244  { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2245  { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2246  { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2247  { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2248  { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2249  { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2250  { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2251  { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2252  { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2253  { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2254  { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2255  { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2256  { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2257  { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2258  { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2259  { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2260  { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2261  { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2262  { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2263  { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2264  { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2265  { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2266  { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2267  { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2268  { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2269  { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2270  { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2271  { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2272  { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2273  { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2274  { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2275  { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2276  { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2277  { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2278  { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2279  { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2280  { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2281  { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2282  { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2283  { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2284  { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2285  { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2286  { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2287  { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2288  { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2289  { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2290  { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2291  { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2292  { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2293  { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2294  { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2295  { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2296  { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2297  { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2298  { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2299  { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2300  { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2301  { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2302  { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2303  { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2304  { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2305  { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2306  { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2307  { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2308  { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2309  { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2310  { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2311  { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2312  { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2313  { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2314  { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2315  { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2316  { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2317  { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2318  { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2319  { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2320  { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2321  { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2322  { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2323  { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2324  { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2325  { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2326  { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2327  { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2328  { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2329  { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2330  { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2331  { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2332  { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2333  { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2334  { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2335  { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2336  { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2337  { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2338  { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2339  { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2340  { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2341  { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2342  { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2343  { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2344  { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2345  { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2346  { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2347  { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2348  { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2349  { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2350  { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2351  { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2352  { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2353  { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2354  { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2355  { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2356  { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2357  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2358  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2359  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2360  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2361  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2362  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2363  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2364  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2365  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2366  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2367  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2368  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2369  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2370  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2371  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2372  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2373  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2374  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2375  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2376  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2377  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2378  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2379  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2380  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2381  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2382  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2383  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2384  { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2385  { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2386  { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2387  { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2388  { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2389  { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2390  { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2391  { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2392  { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2393  { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2394  { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2395  { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2396  { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2397  { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2398  { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2399  { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2400  { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2401  { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2402  { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2403  { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2404  { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2405  { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2406  { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2407  { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2408  { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2409  { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2410  { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2411  { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2412  { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2413  { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2414  { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2415  { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2416  { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2417  { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2418  { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2419  { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2420  { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2421  { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2422  { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2423  { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2424  { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2425  { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2426  { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2427  { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2428  { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2429  { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2430  { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2431  { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2432  { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2433  { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2434  { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2435  { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2436  { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2437  { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2438  { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2439  { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2440  { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2441  { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2442  { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2443  { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2444  { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2445  { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2446  { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2447  { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2448  { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2449  { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2450  { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2451  { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2452  { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2453  { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2454  { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2455  { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2456  { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2457  { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2458  { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2459  { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2460  { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2461  { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2462  { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2463  { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2464  { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2465  { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2466  { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2467  { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2468  { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2469  { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2470  { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2471  { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2472  { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2473  { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2474  { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2475  { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2476  { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2477  { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2478  { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2479  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2480  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2481  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2482  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2483  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2484  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2485  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2486  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2487  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2488  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2489  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2490  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2491  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2492  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2493  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2494  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2495  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2496  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2497  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2498  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2499  { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2500  { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2501  { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2502  { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2503  { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2504  { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2505  { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2506  { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2507  { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2508  { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2509  { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2510  { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2511  { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2512  { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2513  { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2514  { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2515  { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2516  { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2517  { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2518  { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2519  { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2520  { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2521  { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2522  { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2523  { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2524  { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2525  { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2526  { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2527  { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2528  { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2529  { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2530  { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2531  { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2532  { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2533  { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2534  { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2535  { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2536  { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2537  { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2538  { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2539  { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2540  { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2541  { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2542  { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2543  { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2544  { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2545  { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2546  { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2547  { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2548  { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2549  { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2550  { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2551  { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2552  { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2553  { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2554  { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2555  { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2556  { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2557  { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2558  { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2559  { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2560  { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2561  { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2562  { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2563  { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2564  { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2565  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2566  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2567  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2568  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2569  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2570  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2571  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2572  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2573  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2574  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2575  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2576  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2577  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2578  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2579  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2580  { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2581  { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2582  { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2583  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2584  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2585  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2586  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2587  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2588  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2589  { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2590  { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2591  { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2592  { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2593  { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2594  { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2595  { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2596  { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2597  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2598  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2599  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2600  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2601  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2602  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2603  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2604  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2605  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2606  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2607  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2608  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2609  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2610  { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2611  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2612  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2613  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2614  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2615  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2616  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2617  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2618  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2619  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2620  { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2621  { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2622  { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2623  { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2624  { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2625  { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2626  { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2627  { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2628  { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2629  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2630  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2631  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2632  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2633  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2634  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2635  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2636  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2637  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2638  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2639  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2640  { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2641  { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2642  { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2643  { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2644  { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2645  { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2646  { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2647  { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2648  { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2649  { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2650  { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2651  { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2652  { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2653  { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2654  { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2655  { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2656  { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2657  { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2658  { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2659  { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2660  { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2661  { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2662  { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2663  { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2664  { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2665  { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2666  { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2667  { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2668  { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2669  { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2670  { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2671  { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2672  { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2673  { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2674  { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2675  { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2676  { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2677  { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2678  { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2679  { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2680  { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2681  { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2682  { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2683  { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2684  { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2685  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2686  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2687  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2688  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2689  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2690  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2691  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2692  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2693  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2694  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2695  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2696  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2697  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2698  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2699  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2700  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2701  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2702  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2703  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2704  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2705  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2706  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2707  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2708  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2709  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2710  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2711  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2712  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2713  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2714  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2715  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2716  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2717  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2718  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2719  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2720  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2721  { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2722  { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2723  { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2724  { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2725  { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2726  { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2727  { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2728  { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2729  { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2730  { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2731  { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2732  { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2733  { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2734  { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2735  { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2736  { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2737  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2738  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2739  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2740  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2741  { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2742  { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2743  { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2744  { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2745  { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2746  { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2747  { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2748  { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2749  { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2750  { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2751  { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2752  { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2753  { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2754  { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2755  { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2756  { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2757  { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2758  { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2759  { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2760  { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2761  { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2762  { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2763  { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2764  { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2765  { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2766  { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2767  { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2768  { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2769  { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2770  { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2771  { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2772  { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2773  { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2774  { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2775  { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2776  { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2777  { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2778  { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2779  { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2780  { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2781  { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2782  { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2783  { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2784  { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2785  { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2786  { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2787  { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2788  { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2789  { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2790  { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2791  { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2792  { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2793  { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2794  { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2795  { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2796  { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2797  { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2798  { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2799  { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2800  { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2801  { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2802  { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2803  { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2804  { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2805  { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2806  { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2807  { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2808  { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2809  { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2810  { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2811  { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2812  { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2813  { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2814  { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2815  { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2816  { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2817  { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2818  { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2819  { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2820  { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2821  { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2822  { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2823  { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2824  { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2825  { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2826  { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2827  { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2828  { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2829  { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2830  { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2831  { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2832  { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2833  { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2834  { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2835  { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2836  { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2837  { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2838  { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2839  { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2840  { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2841  { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2842  { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2843  { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2844  { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2845  { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2846  { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2847  { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2848  { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2849  };
2850 
2851  // Sort the tables on first execution so we can binary search them.
2852  auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2853  return LHS.BuiltinID < RHS.BuiltinID;
2854  };
2855  static const bool SortOnce =
2856  (llvm::sort(ValidCPU, SortCmp),
2857  llvm::sort(ValidHVX, SortCmp), true);
2858  (void)SortOnce;
2859  auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2860  return BI.BuiltinID < BuiltinID;
2861  };
2862 
2863  const TargetInfo &TI = Context.getTargetInfo();
2864 
2865  const BuiltinAndString *FC =
2866  llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
2867  if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2868  const TargetOptions &Opts = TI.getTargetOpts();
2869  StringRef CPU = Opts.CPU;
2870  if (!CPU.empty()) {
2871  assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2872  CPU.consume_front("hexagon");
2874  StringRef(FC->Str).split(CPUs, ',');
2875  if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2876  return Diag(TheCall->getBeginLoc(),
2877  diag::err_hexagon_builtin_unsupported_cpu);
2878  }
2879  }
2880 
2881  const BuiltinAndString *FH =
2882  llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
2883  if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2884  if (!TI.hasFeature("hvx"))
2885  return Diag(TheCall->getBeginLoc(),
2886  diag::err_hexagon_builtin_requires_hvx);
2887 
2889  StringRef(FH->Str).split(HVXs, ',');
2890  bool IsValid = llvm::any_of(HVXs,
2891  [&TI] (StringRef V) {
2892  std::string F = "hvx" + V.str();
2893  return TI.hasFeature(F);
2894  });
2895  if (!IsValid)
2896  return Diag(TheCall->getBeginLoc(),
2897  diag::err_hexagon_builtin_unsupported_hvx);
2898  }
2899 
2900  return false;
2901 }
2902 
2903 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2904  struct ArgInfo {
2905  uint8_t OpNum;
2906  bool IsSigned;
2907  uint8_t BitWidth;
2908  uint8_t Align;
2909  };
2910  struct BuiltinInfo {
2911  unsigned BuiltinID;
2912  ArgInfo Infos[2];
2913  };
2914 
2915  static BuiltinInfo Infos[] = {
2916  { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2917  { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2918  { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2919  { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
2920  { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2921  { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2922  { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2923  { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2924  { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2925  { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2926  { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2927 
2928  { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2929  { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2930  { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2931  { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2932  { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2933  { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2934  { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2935  { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2936  { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2937  { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2938  { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2939 
2940  { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2941  { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2942  { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2943  { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2944  { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2945  { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2946  { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2947  { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2948  { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2949  { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2950  { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2951  { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2952  { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2953  { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2954  { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2955  { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2956  { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2957  { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2958  { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2959  { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2960  { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2961  { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2962  { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2963  { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2964  { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2965  { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2966  { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2967  { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2968  { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2969  { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2970  { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2971  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2972  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2973  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2974  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2975  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2976  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2977  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2978  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2979  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2980  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2981  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2982  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2983  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2984  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2985  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2986  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2987  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2988  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2989  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2990  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2991  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2992  {{ 1, false, 6, 0 }} },
2993  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2994  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2995  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2996  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2997  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2998  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2999  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
3000  {{ 1, false, 5, 0 }} },
3001  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
3002  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
3003  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
3004  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
3005  { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
3006  { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
3007  { 2, false, 5, 0 }} },
3008  { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
3009  { 2, false, 6, 0 }} },
3010  { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
3011  { 3, false, 5, 0 }} },
3012  { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
3013  { 3, false, 6, 0 }} },
3014  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
3015  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
3016  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
3017  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
3018  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
3019  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
3020  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
3021  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
3022  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
3023  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
3024  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
3025  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
3026  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
3027  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
3028  { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
3029  { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3030  {{ 2, false, 4, 0 },
3031  { 3, false, 5, 0 }} },
3032  { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3033  {{ 2, false, 4, 0 },
3034  { 3, false, 5, 0 }} },
3035  { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3036  {{ 2, false, 4, 0 },
3037  { 3, false, 5, 0 }} },
3038  { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3039  {{ 2, false, 4, 0 },
3040  { 3, false, 5, 0 }} },
3041  { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
3042  { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
3043  { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
3044  { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
3045  { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
3046  { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
3047  { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
3048  { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
3049  { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
3050  { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
3051  { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
3052  { 2, false, 5, 0 }} },
3053  { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
3054  { 2, false, 6, 0 }} },
3055  { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
3056  { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
3057  { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
3058  { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
3059  { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
3060  { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
3061  { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
3062  { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
3063  { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3064  {{ 1, false, 4, 0 }} },
3065  { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
3066  { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3067  {{ 1, false, 4, 0 }} },
3068  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
3069  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
3070  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
3071  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
3072  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
3073  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
3074  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
3075  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
3076  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
3077  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
3078  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
3079  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
3080  { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
3081  { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
3082  { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
3083  { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
3084  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
3085  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
3086  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
3087  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3088  {{ 3, false, 1, 0 }} },
3089  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
3090  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
3091  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
3092  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3093  {{ 3, false, 1, 0 }} },
3094  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
3095  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
3096  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
3097  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3098  {{ 3, false, 1, 0 }} },
3099  };
3100 
3101  // Use a dynamically initialized static to sort the table exactly once on
3102  // first run.
3103  static const bool SortOnce =
3104  (llvm::sort(Infos,
3105  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3106  return LHS.BuiltinID < RHS.BuiltinID;
3107  }),
3108  true);
3109  (void)SortOnce;
3110 
3111  const BuiltinInfo *F = llvm::partition_point(
3112  Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3113  if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3114  return false;
3115 
3116  bool Error = false;
3117 
3118  for (const ArgInfo &A : F->Infos) {
3119  // Ignore empty ArgInfo elements.
3120  if (A.BitWidth == 0)
3121  continue;
3122 
3123  int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3124  int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3125  if (!A.Align) {
3126  Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3127  } else {
3128  unsigned M = 1 << A.Align;
3129  Min *= M;
3130  Max *= M;
3131  Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
3132  SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3133  }
3134  }
3135  return Error;
3136 }
3137 
3138 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3139  CallExpr *TheCall) {
3140  return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
3141  CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3142 }
3143 
3144 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3145  return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
3146  CheckMipsBuiltinArgument(BuiltinID, TheCall);
3147 }
3148 
3149 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
3150  const TargetInfo &TI = Context.getTargetInfo();
3151 
3152  if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3153  BuiltinID <= Mips::BI__builtin_mips_lwx) {
3154  if (!TI.hasFeature("dsp"))
3155  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3156  }
3157 
3158  if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3159  BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3160  if (!TI.hasFeature("dspr2"))
3161  return Diag(TheCall->getBeginLoc(),
3162  diag::err_mips_builtin_requires_dspr2);
3163  }
3164 
3165  if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3166  BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3167  if (!TI.hasFeature("msa"))
3168  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3169  }
3170 
3171  return false;
3172 }
3173 
3174 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3175 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3176 // ordering for DSP is unspecified. MSA is ordered by the data format used
3177 // by the underlying instruction i.e., df/m, df/n and then by size.
3178 //
3179 // FIXME: The size tests here should instead be tablegen'd along with the
3180 // definitions from include/clang/Basic/BuiltinsMips.def.
3181 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3182 // be too.
3183 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3184  unsigned i = 0, l = 0, u = 0, m = 0;
3185  switch (BuiltinID) {
3186  default: return false;
3187  case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3188  case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3189  case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3190  case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3191  case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3192  case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3193  case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3194  // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3195  // df/m field.
3196  // These intrinsics take an unsigned 3 bit immediate.
3197  case Mips::BI__builtin_msa_bclri_b:
3198  case Mips::BI__builtin_msa_bnegi_b:
3199  case Mips::BI__builtin_msa_bseti_b:
3200  case Mips::BI__builtin_msa_sat_s_b:
3201  case Mips::BI__builtin_msa_sat_u_b:
3202  case Mips::BI__builtin_msa_slli_b:
3203  case Mips::BI__builtin_msa_srai_b:
3204  case Mips::BI__builtin_msa_srari_b:
3205  case Mips::BI__builtin_msa_srli_b:
3206  case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3207  case Mips::BI__builtin_msa_binsli_b:
3208  case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3209  // These intrinsics take an unsigned 4 bit immediate.
3210  case Mips::BI__builtin_msa_bclri_h:
3211  case Mips::BI__builtin_msa_bnegi_h:
3212  case Mips::BI__builtin_msa_bseti_h:
3213  case Mips::BI__builtin_msa_sat_s_h:
3214  case Mips::BI__builtin_msa_sat_u_h:
3215  case Mips::BI__builtin_msa_slli_h:
3216  case Mips::BI__builtin_msa_srai_h:
3217  case Mips::BI__builtin_msa_srari_h:
3218  case Mips::BI__builtin_msa_srli_h:
3219  case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3220  case Mips::BI__builtin_msa_binsli_h:
3221  case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3222  // These intrinsics take an unsigned 5 bit immediate.
3223  // The first block of intrinsics actually have an unsigned 5 bit field,
3224  // not a df/n field.
3225  case Mips::BI__builtin_msa_cfcmsa:
3226  case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3227  case Mips::BI__builtin_msa_clei_u_b:
3228  case Mips::BI__builtin_msa_clei_u_h:
3229  case Mips::BI__builtin_msa_clei_u_w:
3230  case Mips::BI__builtin_msa_clei_u_d:
3231  case Mips::BI__builtin_msa_clti_u_b:
3232  case Mips::BI__builtin_msa_clti_u_h:
3233  case Mips::BI__builtin_msa_clti_u_w:
3234  case Mips::BI__builtin_msa_clti_u_d:
3235  case Mips::BI__builtin_msa_maxi_u_b:
3236  case Mips::BI__builtin_msa_maxi_u_h:
3237  case Mips::BI__builtin_msa_maxi_u_w:
3238  case Mips::BI__builtin_msa_maxi_u_d:
3239  case Mips::BI__builtin_msa_mini_u_b:
3240  case Mips::BI__builtin_msa_mini_u_h:
3241  case Mips::BI__builtin_msa_mini_u_w:
3242  case Mips::BI__builtin_msa_mini_u_d:
3243  case Mips::BI__builtin_msa_addvi_b:
3244  case Mips::BI__builtin_msa_addvi_h:
3245  case Mips::BI__builtin_msa_addvi_w:
3246  case Mips::BI__builtin_msa_addvi_d:
3247  case Mips::BI__builtin_msa_bclri_w:
3248  case Mips::BI__builtin_msa_bnegi_w:
3249  case Mips::BI__builtin_msa_bseti_w:
3250  case Mips::BI__builtin_msa_sat_s_w:
3251  case Mips::BI__builtin_msa_sat_u_w:
3252  case Mips::BI__builtin_msa_slli_w:
3253  case Mips::BI__builtin_msa_srai_w:
3254  case Mips::BI__builtin_msa_srari_w:
3255  case Mips::BI__builtin_msa_srli_w:
3256  case Mips::BI__builtin_msa_srlri_w:
3257  case Mips::BI__builtin_msa_subvi_b:
3258  case Mips::BI__builtin_msa_subvi_h:
3259  case Mips::BI__builtin_msa_subvi_w:
3260  case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3261  case Mips::BI__builtin_msa_binsli_w:
3262  case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3263  // These intrinsics take an unsigned 6 bit immediate.
3264  case Mips::BI__builtin_msa_bclri_d:
3265  case Mips::BI__builtin_msa_bnegi_d:
3266  case Mips::BI__builtin_msa_bseti_d:
3267  case Mips::BI__builtin_msa_sat_s_d:
3268  case Mips::BI__builtin_msa_sat_u_d:
3269  case Mips::BI__builtin_msa_slli_d:
3270  case Mips::BI__builtin_msa_srai_d:
3271  case Mips::BI__builtin_msa_srari_d:
3272  case Mips::BI__builtin_msa_srli_d:
3273  case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3274  case Mips::BI__builtin_msa_binsli_d:
3275  case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3276  // These intrinsics take a signed 5 bit immediate.
3277  case Mips::BI__builtin_msa_ceqi_b:
3278  case Mips::BI__builtin_msa_ceqi_h:
3279  case Mips::BI__builtin_msa_ceqi_w:
3280  case Mips::BI__builtin_msa_ceqi_d:
3281  case Mips::BI__builtin_msa_clti_s_b:
3282  case Mips::BI__builtin_msa_clti_s_h:
3283  case Mips::BI__builtin_msa_clti_s_w:
3284  case Mips::BI__builtin_msa_clti_s_d:
3285  case Mips::BI__builtin_msa_clei_s_b:
3286  case Mips::BI__builtin_msa_clei_s_h:
3287  case Mips::BI__builtin_msa_clei_s_w:
3288  case Mips::BI__builtin_msa_clei_s_d:
3289  case Mips::BI__builtin_msa_maxi_s_b:
3290  case Mips::BI__builtin_msa_maxi_s_h:
3291  case Mips::BI__builtin_msa_maxi_s_w:
3292  case Mips::BI__builtin_msa_maxi_s_d:
3293  case Mips::BI__builtin_msa_mini_s_b:
3294  case Mips::BI__builtin_msa_mini_s_h:
3295  case Mips::BI__builtin_msa_mini_s_w:
3296  case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3297  // These intrinsics take an unsigned 8 bit immediate.
3298  case Mips::BI__builtin_msa_andi_b:
3299  case Mips::BI__builtin_msa_nori_b:
3300  case Mips::BI__builtin_msa_ori_b:
3301  case Mips::BI__builtin_msa_shf_b:
3302  case Mips::BI__builtin_msa_shf_h:
3303  case Mips::BI__builtin_msa_shf_w:
3304  case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3305  case Mips::BI__builtin_msa_bseli_b:
3306  case Mips::BI__builtin_msa_bmnzi_b:
3307  case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3308  // df/n format
3309  // These intrinsics take an unsigned 4 bit immediate.
3310  case Mips::BI__builtin_msa_copy_s_b:
3311  case Mips::BI__builtin_msa_copy_u_b:
3312  case Mips::BI__builtin_msa_insve_b:
3313  case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3314  case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3315  // These intrinsics take an unsigned 3 bit immediate.
3316  case Mips::BI__builtin_msa_copy_s_h:
3317  case Mips::BI__builtin_msa_copy_u_h:
3318  case Mips::BI__builtin_msa_insve_h:
3319  case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3320  case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3321  // These intrinsics take an unsigned 2 bit immediate.
3322  case Mips::BI__builtin_msa_copy_s_w:
3323  case Mips::BI__builtin_msa_copy_u_w:
3324  case Mips::BI__builtin_msa_insve_w:
3325  case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3326  case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3327  // These intrinsics take an unsigned 1 bit immediate.
3328  case Mips::BI__builtin_msa_copy_s_d:
3329  case Mips::BI__builtin_msa_copy_u_d:
3330  case Mips::BI__builtin_msa_insve_d:
3331  case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3332  case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3333  // Memory offsets and immediate loads.
3334  // These intrinsics take a signed 10 bit immediate.
3335  case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3336  case Mips::BI__builtin_msa_ldi_h:
3337  case Mips::BI__builtin_msa_ldi_w:
3338  case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3339  case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3340  case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3341  case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3342  case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3343  case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3344  case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3345  case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3346  case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3347  }
3348 
3349  if (!m)
3350  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3351 
3352  return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3353  SemaBuiltinConstantArgMultiple(TheCall, i, m);
3354 }
3355 
3356 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3357  unsigned i = 0, l = 0, u = 0;
3358  bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3359  BuiltinID == PPC::BI__builtin_divdeu ||
3360  BuiltinID == PPC::BI__builtin_bpermd;
3361  bool IsTarget64Bit = Context.getTargetInfo()
3362  .getTypeWidth(Context
3363  .getTargetInfo()
3364  .getIntPtrType()) == 64;
3365  bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3366  BuiltinID == PPC::BI__builtin_divweu ||
3367  BuiltinID == PPC::BI__builtin_divde ||
3368  BuiltinID == PPC::BI__builtin_divdeu;
3369 
3370  if (Is64BitBltin && !IsTarget64Bit)
3371  return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3372  << TheCall->getSourceRange();
3373 
3374  if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3375  (BuiltinID == PPC::BI__builtin_bpermd &&
3376  !Context.getTargetInfo().hasFeature("bpermd")))
3377  return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3378  << TheCall->getSourceRange();
3379 
3380  auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3381  if (!Context.getTargetInfo().hasFeature("vsx"))
3382  return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3383  << TheCall->getSourceRange();
3384  return false;
3385  };
3386 
3387  switch (BuiltinID) {
3388  default: return false;
3389  case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3390  case PPC::BI__builtin_altivec_crypto_vshasigmad:
3391  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3392  SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3393  case PPC::BI__builtin_altivec_dss:
3394  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3395  case PPC::BI__builtin_tbegin:
3396  case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3397  case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3398  case PPC::BI__builtin_tabortwc:
3399  case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3400  case PPC::BI__builtin_tabortwci:
3401  case PPC::BI__builtin_tabortdci:
3402  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3403  SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3404  case PPC::BI__builtin_altivec_dst:
3405  case PPC::BI__builtin_altivec_dstt:
3406  case PPC::BI__builtin_altivec_dstst:
3407  case PPC::BI__builtin_altivec_dststt:
3408  return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3409  case PPC::BI__builtin_vsx_xxpermdi:
3410  case PPC::BI__builtin_vsx_xxsldwi:
3411  return SemaBuiltinVSX(TheCall);
3412  case PPC::BI__builtin_unpack_vector_int128:
3413  return SemaVSXCheck(TheCall) ||
3414  SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3415  case PPC::BI__builtin_pack_vector_int128:
3416  return SemaVSXCheck(TheCall);
3417  }
3418  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3419 }
3420 
3421 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3422  CallExpr *TheCall) {
3423  if (BuiltinID == SystemZ::BI__builtin_tabort) {
3424  Expr *Arg = TheCall->getArg(0);
3425  llvm::APSInt AbortCode(32);
3426  if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3427  AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3428  return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3429  << Arg->getSourceRange();
3430  }
3431 
3432  // For intrinsics which take an immediate value as part of the instruction,
3433  // range check them here.
3434  unsigned i = 0, l = 0, u = 0;
3435  switch (BuiltinID) {
3436  default: return false;
3437  case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3438  case SystemZ::BI__builtin_s390_verimb:
3439  case SystemZ::BI__builtin_s390_verimh:
3440  case SystemZ::BI__builtin_s390_verimf:
3441  case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3442  case SystemZ::BI__builtin_s390_vfaeb:
3443  case SystemZ::BI__builtin_s390_vfaeh:
3444  case SystemZ::BI__builtin_s390_vfaef:
3445  case SystemZ::BI__builtin_s390_vfaebs:
3446  case SystemZ::BI__builtin_s390_vfaehs:
3447  case SystemZ::BI__builtin_s390_vfaefs:
3448  case SystemZ::BI__builtin_s390_vfaezb:
3449  case SystemZ::BI__builtin_s390_vfaezh:
3450  case SystemZ::BI__builtin_s390_vfaezf:
3451  case SystemZ::BI__builtin_s390_vfaezbs:
3452  case SystemZ::BI__builtin_s390_vfaezhs:
3453  case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3454  case SystemZ::BI__builtin_s390_vfisb:
3455  case SystemZ::BI__builtin_s390_vfidb:
3456  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3457  SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3458  case SystemZ::BI__builtin_s390_vftcisb:
3459  case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3460  case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3461  case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3462  case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3463  case SystemZ::BI__builtin_s390_vstrcb:
3464  case SystemZ::BI__builtin_s390_vstrch:
3465  case SystemZ::BI__builtin_s390_vstrcf:
3466  case SystemZ::BI__builtin_s390_vstrczb:
3467  case SystemZ::BI__builtin_s390_vstrczh:
3468  case SystemZ::BI__builtin_s390_vstrczf:
3469  case SystemZ::BI__builtin_s390_vstrcbs:
3470  case SystemZ::BI__builtin_s390_vstrchs:
3471  case SystemZ::BI__builtin_s390_vstrcfs:
3472  case SystemZ::BI__builtin_s390_vstrczbs:
3473  case SystemZ::BI__builtin_s390_vstrczhs:
3474  case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3475  case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3476  case SystemZ::BI__builtin_s390_vfminsb:
3477  case SystemZ::BI__builtin_s390_vfmaxsb:
3478  case SystemZ::BI__builtin_s390_vfmindb:
3479  case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3480  case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3481  case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3482  }
3483  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3484 }
3485 
3486 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3487 /// This checks that the target supports __builtin_cpu_supports and
3488 /// that the string argument is constant and valid.
3489 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3490  Expr *Arg = TheCall->getArg(0);
3491 
3492  // Check if the argument is a string literal.
3493  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3494  return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3495  << Arg->getSourceRange();
3496 
3497  // Check the contents of the string.
3498  StringRef Feature =
3499  cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3500  if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3501  return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3502  << Arg->getSourceRange();
3503  return false;
3504 }
3505 
3506 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3507 /// This checks that the target supports __builtin_cpu_is and
3508 /// that the string argument is constant and valid.
3509 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3510  Expr *Arg = TheCall->getArg(0);
3511 
3512  // Check if the argument is a string literal.
3513  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3514  return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3515  << Arg->getSourceRange();
3516 
3517  // Check the contents of the string.
3518  StringRef Feature =
3519  cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3520  if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3521  return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3522  << Arg->getSourceRange();
3523  return false;
3524 }
3525 
3526 // Check if the rounding mode is legal.
3527 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3528  // Indicates if this instruction has rounding control or just SAE.
3529  bool HasRC = false;
3530 
3531  unsigned ArgNum = 0;
3532  switch (BuiltinID) {
3533  default:
3534  return false;
3535  case X86::BI__builtin_ia32_vcvttsd2si32:
3536  case X86::BI__builtin_ia32_vcvttsd2si64:
3537  case X86::BI__builtin_ia32_vcvttsd2usi32:
3538  case X86::BI__builtin_ia32_vcvttsd2usi64:
3539  case X86::BI__builtin_ia32_vcvttss2si32:
3540  case X86::BI__builtin_ia32_vcvttss2si64:
3541  case X86::BI__builtin_ia32_vcvttss2usi32:
3542  case X86::BI__builtin_ia32_vcvttss2usi64:
3543  ArgNum = 1;
3544  break;
3545  case X86::BI__builtin_ia32_maxpd512:
3546  case X86::BI__builtin_ia32_maxps512:
3547  case X86::BI__builtin_ia32_minpd512:
3548  case X86::BI__builtin_ia32_minps512:
3549  ArgNum = 2;
3550  break;
3551  case X86::BI__builtin_ia32_cvtps2pd512_mask:
3552  case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3553  case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3554  case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3555  case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3556  case X86::BI__builtin_ia32_cvttps2dq512_mask:
3557  case X86::BI__builtin_ia32_cvttps2qq512_mask:
3558  case X86::BI__builtin_ia32_cvttps2udq512_mask:
3559  case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3560  case X86::BI__builtin_ia32_exp2pd_mask:
3561  case X86::BI__builtin_ia32_exp2ps_mask:
3562  case X86::BI__builtin_ia32_getexppd512_mask:
3563  case X86::BI__builtin_ia32_getexpps512_mask:
3564  case X86::BI__builtin_ia32_rcp28pd_mask:
3565  case X86::BI__builtin_ia32_rcp28ps_mask:
3566  case X86::BI__builtin_ia32_rsqrt28pd_mask:
3567  case X86::BI__builtin_ia32_rsqrt28ps_mask:
3568  case X86::BI__builtin_ia32_vcomisd:
3569  case X86::BI__builtin_ia32_vcomiss:
3570  case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3571  ArgNum = 3;
3572  break;
3573  case X86::BI__builtin_ia32_cmppd512_mask:
3574  case X86::BI__builtin_ia32_cmpps512_mask:
3575  case X86::BI__builtin_ia32_cmpsd_mask:
3576  case X86::BI__builtin_ia32_cmpss_mask:
3577  case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3578  case X86::BI__builtin_ia32_getexpsd128_round_mask:
3579  case X86::BI__builtin_ia32_getexpss128_round_mask:
3580  case X86::BI__builtin_ia32_getmantpd512_mask:
3581  case X86::BI__builtin_ia32_getmantps512_mask:
3582  case X86::BI__builtin_ia32_maxsd_round_mask:
3583  case X86::BI__builtin_ia32_maxss_round_mask:
3584  case X86::BI__builtin_ia32_minsd_round_mask:
3585  case X86::BI__builtin_ia32_minss_round_mask:
3586  case X86::BI__builtin_ia32_rcp28sd_round_mask:
3587  case X86::BI__builtin_ia32_rcp28ss_round_mask:
3588  case X86::BI__builtin_ia32_reducepd512_mask:
3589  case X86::BI__builtin_ia32_reduceps512_mask:
3590  case X86::BI__builtin_ia32_rndscalepd_mask:
3591  case X86::BI__builtin_ia32_rndscaleps_mask:
3592  case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3593  case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3594  ArgNum = 4;
3595  break;
3596  case X86::BI__builtin_ia32_fixupimmpd512_mask:
3597  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3598  case X86::BI__builtin_ia32_fixupimmps512_mask:
3599  case X86::BI__builtin_ia32_fixupimmps512_maskz:
3600  case X86::BI__builtin_ia32_fixupimmsd_mask:
3601  case X86::BI__builtin_ia32_fixupimmsd_maskz:
3602  case X86::BI__builtin_ia32_fixupimmss_mask:
3603  case X86::BI__builtin_ia32_fixupimmss_maskz:
3604  case X86::BI__builtin_ia32_getmantsd_round_mask:
3605  case X86::BI__builtin_ia32_getmantss_round_mask:
3606  case X86::BI__builtin_ia32_rangepd512_mask:
3607  case X86::BI__builtin_ia32_rangeps512_mask:
3608  case X86::BI__builtin_ia32_rangesd128_round_mask:
3609  case X86::BI__builtin_ia32_rangess128_round_mask:
3610  case X86::BI__builtin_ia32_reducesd_mask:
3611  case X86::BI__builtin_ia32_reducess_mask:
3612  case X86::BI__builtin_ia32_rndscalesd_round_mask:
3613  case X86::BI__builtin_ia32_rndscaless_round_mask:
3614  ArgNum = 5;
3615  break;
3616  case X86::BI__builtin_ia32_vcvtsd2si64:
3617  case X86::BI__builtin_ia32_vcvtsd2si32:
3618  case X86::BI__builtin_ia32_vcvtsd2usi32:
3619  case X86::BI__builtin_ia32_vcvtsd2usi64:
3620  case X86::BI__builtin_ia32_vcvtss2si32:
3621  case X86::BI__builtin_ia32_vcvtss2si64:
3622  case X86::BI__builtin_ia32_vcvtss2usi32:
3623  case X86::BI__builtin_ia32_vcvtss2usi64:
3624  case X86::BI__builtin_ia32_sqrtpd512:
3625  case X86::BI__builtin_ia32_sqrtps512:
3626  ArgNum = 1;
3627  HasRC = true;
3628  break;
3629  case X86::BI__builtin_ia32_addpd512:
3630  case X86::BI__builtin_ia32_addps512:
3631  case X86::BI__builtin_ia32_divpd512:
3632  case X86::BI__builtin_ia32_divps512:
3633  case X86::BI__builtin_ia32_mulpd512:
3634  case X86::BI__builtin_ia32_mulps512:
3635  case X86::BI__builtin_ia32_subpd512:
3636  case X86::BI__builtin_ia32_subps512:
3637  case X86::BI__builtin_ia32_cvtsi2sd64:
3638  case X86::BI__builtin_ia32_cvtsi2ss32:
3639  case X86::BI__builtin_ia32_cvtsi2ss64:
3640  case X86::BI__builtin_ia32_cvtusi2sd64:
3641  case X86::BI__builtin_ia32_cvtusi2ss32:
3642  case X86::BI__builtin_ia32_cvtusi2ss64:
3643  ArgNum = 2;
3644  HasRC = true;
3645  break;
3646  case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3647  case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3648  case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3649  case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3650  case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3651  case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3652  case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3653  case X86::BI__builtin_ia32_cvtps2dq512_mask:
3654  case X86::BI__builtin_ia32_cvtps2qq512_mask:
3655  case X86::BI__builtin_ia32_cvtps2udq512_mask:
3656  case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3657  case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3658  case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3659  case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3660  case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3661  ArgNum = 3;
3662  HasRC = true;
3663  break;
3664  case X86::BI__builtin_ia32_addss_round_mask:
3665  case X86::BI__builtin_ia32_addsd_round_mask:
3666  case X86::BI__builtin_ia32_divss_round_mask:
3667  case X86::BI__builtin_ia32_divsd_round_mask:
3668  case X86::BI__builtin_ia32_mulss_round_mask:
3669  case X86::BI__builtin_ia32_mulsd_round_mask:
3670  case X86::BI__builtin_ia32_subss_round_mask:
3671  case X86::BI__builtin_ia32_subsd_round_mask:
3672  case X86::BI__builtin_ia32_scalefpd512_mask:
3673  case X86::BI__builtin_ia32_scalefps512_mask:
3674  case X86::BI__builtin_ia32_scalefsd_round_mask:
3675  case X86::BI__builtin_ia32_scalefss_round_mask:
3676  case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3677  case X86::BI__builtin_ia32_sqrtsd_round_mask:
3678  case X86::BI__builtin_ia32_sqrtss_round_mask:
3679  case X86::BI__builtin_ia32_vfmaddsd3_mask:
3680  case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3681  case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3682  case X86::BI__builtin_ia32_vfmaddss3_mask:
3683  case X86::BI__builtin_ia32_vfmaddss3_maskz:
3684  case X86::BI__builtin_ia32_vfmaddss3_mask3:
3685  case X86::BI__builtin_ia32_vfmaddpd512_mask:
3686  case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3687  case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3688  case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3689  case X86::BI__builtin_ia32_vfmaddps512_mask:
3690  case X86::BI__builtin_ia32_vfmaddps512_maskz:
3691  case X86::BI__builtin_ia32_vfmaddps512_mask3:
3692  case X86::BI__builtin_ia32_vfmsubps512_mask3:
3693  case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3694  case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3695  case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3696  case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3697  case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3698  case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3699  case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3700  case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3701  ArgNum = 4;
3702  HasRC = true;
3703  break;
3704  }
3705 
3706  llvm::APSInt Result;
3707 
3708  // We can't check the value of a dependent argument.
3709  Expr *Arg = TheCall->getArg(ArgNum);
3710  if (Arg->isTypeDependent() || Arg->isValueDependent())
3711  return false;
3712 
3713  // Check constant-ness first.
3714  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3715  return true;
3716 
3717  // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3718  // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3719  // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3720  // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3721  if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3722  Result == 8/*ROUND_NO_EXC*/ ||
3723  (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3724  (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3725  return false;
3726 
3727  return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3728  << Arg->getSourceRange();
3729 }
3730 
3731 // Check if the gather/scatter scale is legal.
3732 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3733  CallExpr *TheCall) {
3734  unsigned ArgNum = 0;
3735  switch (BuiltinID) {
3736  default:
3737  return false;
3738  case X86::BI__builtin_ia32_gatherpfdpd:
3739  case X86::BI__builtin_ia32_gatherpfdps:
3740  case X86::BI__builtin_ia32_gatherpfqpd:
3741  case X86::BI__builtin_ia32_gatherpfqps:
3742  case X86::BI__builtin_ia32_scatterpfdpd:
3743  case X86::BI__builtin_ia32_scatterpfdps:
3744  case X86::BI__builtin_ia32_scatterpfqpd:
3745  case X86::BI__builtin_ia32_scatterpfqps:
3746  ArgNum = 3;
3747  break;
3748  case X86::BI__builtin_ia32_gatherd_pd:
3749  case X86::BI__builtin_ia32_gatherd_pd256:
3750  case X86::BI__builtin_ia32_gatherq_pd:
3751  case X86::BI__builtin_ia32_gatherq_pd256:
3752  case X86::BI__builtin_ia32_gatherd_ps:
3753  case X86::BI__builtin_ia32_gatherd_ps256:
3754  case X86::BI__builtin_ia32_gatherq_ps:
3755  case X86::BI__builtin_ia32_gatherq_ps256:
3756  case X86::BI__builtin_ia32_gatherd_q:
3757  case X86::BI__builtin_ia32_gatherd_q256:
3758  case X86::BI__builtin_ia32_gatherq_q:
3759  case X86::BI__builtin_ia32_gatherq_q256:
3760  case X86::BI__builtin_ia32_gatherd_d:
3761  case X86::BI__builtin_ia32_gatherd_d256:
3762  case X86::BI__builtin_ia32_gatherq_d:
3763  case X86::BI__builtin_ia32_gatherq_d256:
3764  case X86::BI__builtin_ia32_gather3div2df:
3765  case X86::BI__builtin_ia32_gather3div2di:
3766  case X86::BI__builtin_ia32_gather3div4df:
3767  case X86::BI__builtin_ia32_gather3div4di:
3768  case X86::BI__builtin_ia32_gather3div4sf:
3769  case X86::BI__builtin_ia32_gather3div4si:
3770  case X86::BI__builtin_ia32_gather3div8sf:
3771  case X86::BI__builtin_ia32_gather3div8si:
3772  case X86::BI__builtin_ia32_gather3siv2df:
3773  case X86::BI__builtin_ia32_gather3siv2di:
3774  case X86::BI__builtin_ia32_gather3siv4df:
3775  case X86::BI__builtin_ia32_gather3siv4di:
3776  case X86::BI__builtin_ia32_gather3siv4sf:
3777  case X86::BI__builtin_ia32_gather3siv4si:
3778  case X86::BI__builtin_ia32_gather3siv8sf:
3779  case X86::BI__builtin_ia32_gather3siv8si:
3780  case X86::BI__builtin_ia32_gathersiv8df:
3781  case X86::BI__builtin_ia32_gathersiv16sf:
3782  case X86::BI__builtin_ia32_gatherdiv8df:
3783  case X86::BI__builtin_ia32_gatherdiv16sf:
3784  case X86::BI__builtin_ia32_gathersiv8di:
3785  case X86::BI__builtin_ia32_gathersiv16si:
3786  case X86::BI__builtin_ia32_gatherdiv8di:
3787  case X86::BI__builtin_ia32_gatherdiv16si:
3788  case X86::BI__builtin_ia32_scatterdiv2df:
3789  case X86::BI__builtin_ia32_scatterdiv2di:
3790  case X86::BI__builtin_ia32_scatterdiv4df:
3791  case X86::BI__builtin_ia32_scatterdiv4di:
3792  case X86::BI__builtin_ia32_scatterdiv4sf:
3793  case X86::BI__builtin_ia32_scatterdiv4si:
3794  case X86::BI__builtin_ia32_scatterdiv8sf:
3795  case X86::BI__builtin_ia32_scatterdiv8si:
3796  case X86::BI__builtin_ia32_scattersiv2df:
3797  case X86::BI__builtin_ia32_scattersiv2di:
3798  case X86::BI__builtin_ia32_scattersiv4df:
3799  case X86::BI__builtin_ia32_scattersiv4di:
3800  case X86::BI__builtin_ia32_scattersiv4sf:
3801  case X86::BI__builtin_ia32_scattersiv4si:
3802  case X86::BI__builtin_ia32_scattersiv8sf:
3803  case X86::BI__builtin_ia32_scattersiv8si:
3804  case X86::BI__builtin_ia32_scattersiv8df:
3805  case X86::BI__builtin_ia32_scattersiv16sf:
3806  case X86::BI__builtin_ia32_scatterdiv8df:
3807  case X86::BI__builtin_ia32_scatterdiv16sf:
3808  case X86::BI__builtin_ia32_scattersiv8di:
3809  case X86::BI__builtin_ia32_scattersiv16si:
3810  case X86::BI__builtin_ia32_scatterdiv8di:
3811  case X86::BI__builtin_ia32_scatterdiv16si:
3812  ArgNum = 4;
3813  break;
3814  }
3815 
3816  llvm::APSInt Result;
3817 
3818  // We can't check the value of a dependent argument.
3819  Expr *Arg = TheCall->getArg(ArgNum);
3820  if (Arg->isTypeDependent() || Arg->isValueDependent())
3821  return false;
3822 
3823  // Check constant-ness first.
3824  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3825  return true;
3826 
3827  if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3828  return false;
3829 
3830  return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3831  << Arg->getSourceRange();
3832 }
3833 
3834 static bool isX86_32Builtin(unsigned BuiltinID) {
3835  // These builtins only work on x86-32 targets.
3836  switch (BuiltinID) {
3837  case X86::BI__builtin_ia32_readeflags_u32:
3838  case X86::BI__builtin_ia32_writeeflags_u32:
3839  return true;
3840  }
3841 
3842  return false;
3843 }
3844 
3845 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3846  if (BuiltinID == X86::BI__builtin_cpu_supports)
3847  return SemaBuiltinCpuSupports(*this, TheCall);
3848 
3849  if (BuiltinID == X86::BI__builtin_cpu_is)
3850  return SemaBuiltinCpuIs(*this, TheCall);
3851 
3852  // Check for 32-bit only builtins on a 64-bit target.
3853  const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3854  if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3855  return Diag(TheCall->getCallee()->getBeginLoc(),
3856  diag::err_32_bit_builtin_64_bit_tgt);
3857 
3858  // If the intrinsic has rounding or SAE make sure its valid.
3859  if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3860  return true;
3861 
3862  // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3863  if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3864  return true;
3865 
3866  // For intrinsics which take an immediate value as part of the instruction,
3867  // range check them here.
3868  int i = 0, l = 0, u = 0;
3869  switch (BuiltinID) {
3870  default:
3871  return false;
3872  case X86::BI__builtin_ia32_vec_ext_v2si:
3873  case X86::BI__builtin_ia32_vec_ext_v2di:
3874  case X86::BI__builtin_ia32_vextractf128_pd256:
3875  case X86::BI__builtin_ia32_vextractf128_ps256:
3876  case X86::BI__builtin_ia32_vextractf128_si256:
3877  case X86::BI__builtin_ia32_extract128i256:
3878  case X86::BI__builtin_ia32_extractf64x4_mask:
3879  case X86::BI__builtin_ia32_extracti64x4_mask:
3880  case X86::BI__builtin_ia32_extractf32x8_mask:
3881  case X86::BI__builtin_ia32_extracti32x8_mask:
3882  case X86::BI__builtin_ia32_extractf64x2_256_mask:
3883  case X86::BI__builtin_ia32_extracti64x2_256_mask:
3884  case X86::BI__builtin_ia32_extractf32x4_256_mask:
3885  case X86::BI__builtin_ia32_extracti32x4_256_mask:
3886  i = 1; l = 0; u = 1;
3887  break;
3888  case X86::BI__builtin_ia32_vec_set_v2di:
3889  case X86::BI__builtin_ia32_vinsertf128_pd256:
3890  case X86::BI__builtin_ia32_vinsertf128_ps256:
3891  case X86::BI__builtin_ia32_vinsertf128_si256:
3892  case X86::BI__builtin_ia32_insert128i256:
3893  case X86::BI__builtin_ia32_insertf32x8:
3894  case X86::BI__builtin_ia32_inserti32x8:
3895  case X86::BI__builtin_ia32_insertf64x4:
3896  case X86::BI__builtin_ia32_inserti64x4:
3897  case X86::BI__builtin_ia32_insertf64x2_256:
3898  case X86::BI__builtin_ia32_inserti64x2_256:
3899  case X86::BI__builtin_ia32_insertf32x4_256:
3900  case X86::BI__builtin_ia32_inserti32x4_256:
3901  i = 2; l = 0; u = 1;
3902  break;
3903  case X86::BI__builtin_ia32_vpermilpd:
3904  case X86::BI__builtin_ia32_vec_ext_v4hi:
3905  case X86::BI__builtin_ia32_vec_ext_v4si:
3906  case X86::BI__builtin_ia32_vec_ext_v4sf:
3907  case X86::BI__builtin_ia32_vec_ext_v4di:
3908  case X86::BI__builtin_ia32_extractf32x4_mask:
3909  case X86::BI__builtin_ia32_extracti32x4_mask:
3910  case X86::BI__builtin_ia32_extractf64x2_512_mask:
3911  case X86::BI__builtin_ia32_extracti64x2_512_mask:
3912  i = 1; l = 0; u = 3;
3913  break;
3914  case X86::BI_mm_prefetch:
3915  case X86::BI__builtin_ia32_vec_ext_v8hi:
3916  case X86::BI__builtin_ia32_vec_ext_v8si:
3917  i = 1; l = 0; u = 7;
3918  break;
3919  case X86::BI__builtin_ia32_sha1rnds4:
3920  case X86::BI__builtin_ia32_blendpd:
3921  case X86::BI__builtin_ia32_shufpd:
3922  case X86::BI__builtin_ia32_vec_set_v4hi:
3923  case X86::BI__builtin_ia32_vec_set_v4si:
3924  case X86::BI__builtin_ia32_vec_set_v4di:
3925  case X86::BI__builtin_ia32_shuf_f32x4_256:
3926  case X86::BI__builtin_ia32_shuf_f64x2_256:
3927  case X86::BI__builtin_ia32_shuf_i32x4_256:
3928  case X86::BI__builtin_ia32_shuf_i64x2_256:
3929  case X86::BI__builtin_ia32_insertf64x2_512:
3930  case X86::BI__builtin_ia32_inserti64x2_512:
3931  case X86::BI__builtin_ia32_insertf32x4:
3932  case X86::BI__builtin_ia32_inserti32x4:
3933  i = 2; l = 0; u = 3;
3934  break;
3935  case X86::BI__builtin_ia32_vpermil2pd:
3936  case X86::BI__builtin_ia32_vpermil2pd256:
3937  case X86::BI__builtin_ia32_vpermil2ps:
3938  case X86::BI__builtin_ia32_vpermil2ps256:
3939  i = 3; l = 0; u = 3;
3940  break;
3941  case X86::BI__builtin_ia32_cmpb128_mask:
3942  case X86::BI__builtin_ia32_cmpw128_mask:
3943  case X86::BI__builtin_ia32_cmpd128_mask:
3944  case X86::BI__builtin_ia32_cmpq128_mask:
3945  case X86::BI__builtin_ia32_cmpb256_mask:
3946  case X86::BI__builtin_ia32_cmpw256_mask:
3947  case X86::BI__builtin_ia32_cmpd256_mask:
3948  case X86::BI__builtin_ia32_cmpq256_mask:
3949  case X86::BI__builtin_ia32_cmpb512_mask:
3950  case X86::BI__builtin_ia32_cmpw512_mask:
3951  case X86::BI__builtin_ia32_cmpd512_mask:
3952  case X86::BI__builtin_ia32_cmpq512_mask:
3953  case X86::BI__builtin_ia32_ucmpb128_mask:
3954  case X86::BI__builtin_ia32_ucmpw128_mask:
3955  case X86::BI__builtin_ia32_ucmpd128_mask:
3956  case X86::BI__builtin_ia32_ucmpq128_mask:
3957  case X86::BI__builtin_ia32_ucmpb256_mask:
3958  case X86::BI__builtin_ia32_ucmpw256_mask:
3959  case X86::BI__builtin_ia32_ucmpd256_mask:
3960  case X86::BI__builtin_ia32_ucmpq256_mask:
3961  case X86::BI__builtin_ia32_ucmpb512_mask:
3962  case X86::BI__builtin_ia32_ucmpw512_mask:
3963  case X86::BI__builtin_ia32_ucmpd512_mask:
3964  case X86::BI__builtin_ia32_ucmpq512_mask:
3965  case X86::BI__builtin_ia32_vpcomub:
3966  case X86::BI__builtin_ia32_vpcomuw:
3967  case X86::BI__builtin_ia32_vpcomud:
3968  case X86::BI__builtin_ia32_vpcomuq:
3969  case X86::BI__builtin_ia32_vpcomb:
3970  case X86::BI__builtin_ia32_vpcomw:
3971  case X86::BI__builtin_ia32_vpcomd:
3972  case X86::BI__builtin_ia32_vpcomq:
3973  case X86::BI__builtin_ia32_vec_set_v8hi:
3974  case X86::BI__builtin_ia32_vec_set_v8si:
3975  i = 2; l = 0; u = 7;
3976  break;
3977  case X86::BI__builtin_ia32_vpermilpd256:
3978  case X86::BI__builtin_ia32_roundps:
3979  case X86::BI__builtin_ia32_roundpd:
3980  case X86::BI__builtin_ia32_roundps256:
3981  case X86::BI__builtin_ia32_roundpd256:
3982  case X86::BI__builtin_ia32_getmantpd128_mask:
3983  case X86::BI__builtin_ia32_getmantpd256_mask:
3984  case X86::BI__builtin_ia32_getmantps128_mask:
3985  case X86::BI__builtin_ia32_getmantps256_mask:
3986  case X86::BI__builtin_ia32_getmantpd512_mask:
3987  case X86::BI__builtin_ia32_getmantps512_mask:
3988  case X86::BI__builtin_ia32_vec_ext_v16qi:
3989  case X86::BI__builtin_ia32_vec_ext_v16hi:
3990  i = 1; l = 0; u = 15;
3991  break;
3992  case X86::BI__builtin_ia32_pblendd128:
3993  case X86::BI__builtin_ia32_blendps:
3994  case X86::BI__builtin_ia32_blendpd256:
3995  case X86::BI__builtin_ia32_shufpd256:
3996  case X86::BI__builtin_ia32_roundss:
3997  case X86::BI__builtin_ia32_roundsd:
3998  case X86::BI__builtin_ia32_rangepd128_mask:
3999  case X86::BI__builtin_ia32_rangepd256_mask:
4000  case X86::BI__builtin_ia32_rangepd512_mask:
4001  case X86::BI__builtin_ia32_rangeps128_mask:
4002  case X86::BI__builtin_ia32_rangeps256_mask:
4003  case X86::BI__builtin_ia32_rangeps512_mask:
4004  case X86::BI__builtin_ia32_getmantsd_round_mask:
4005  case X86::BI__builtin_ia32_getmantss_round_mask:
4006  case X86::BI__builtin_ia32_vec_set_v16qi:
4007  case X86::BI__builtin_ia32_vec_set_v16hi:
4008  i = 2; l = 0; u = 15;
4009  break;
4010  case X86::BI__builtin_ia32_vec_ext_v32qi:
4011  i = 1; l = 0; u = 31;
4012  break;
4013  case X86::BI__builtin_ia32_cmpps:
4014  case X86::BI__builtin_ia32_cmpss:
4015  case X86::BI__builtin_ia32_cmppd:
4016  case X86::BI__builtin_ia32_cmpsd:
4017  case X86::BI__builtin_ia32_cmpps256:
4018  case X86::BI__builtin_ia32_cmppd256:
4019  case X86::BI__builtin_ia32_cmpps128_mask:
4020  case X86::BI__builtin_ia32_cmppd128_mask:
4021  case X86::BI__builtin_ia32_cmpps256_mask:
4022  case X86::BI__builtin_ia32_cmppd256_mask:
4023  case X86::BI__builtin_ia32_cmpps512_mask:
4024  case X86::BI__builtin_ia32_cmppd512_mask:
4025  case X86::BI__builtin_ia32_cmpsd_mask:
4026  case X86::BI__builtin_ia32_cmpss_mask:
4027  case X86::BI__builtin_ia32_vec_set_v32qi:
4028  i = 2; l = 0; u = 31;
4029  break;
4030  case X86::BI__builtin_ia32_permdf256:
4031  case X86::BI__builtin_ia32_permdi256:
4032  case X86::BI__builtin_ia32_permdf512:
4033  case X86::BI__builtin_ia32_permdi512:
4034  case X86::BI__builtin_ia32_vpermilps:
4035  case X86::BI__builtin_ia32_vpermilps256:
4036  case X86::BI__builtin_ia32_vpermilpd512:
4037  case X86::BI__builtin_ia32_vpermilps512:
4038  case X86::BI__builtin_ia32_pshufd:
4039  case X86::BI__builtin_ia32_pshufd256:
4040  case X86::BI__builtin_ia32_pshufd512:
4041  case X86::BI__builtin_ia32_pshufhw:
4042  case X86::BI__builtin_ia32_pshufhw256:
4043  case X86::BI__builtin_ia32_pshufhw512:
4044  case X86::BI__builtin_ia32_pshuflw:
4045  case X86::BI__builtin_ia32_pshuflw256:
4046  case X86::BI__builtin_ia32_pshuflw512:
4047  case X86::BI__builtin_ia32_vcvtps2ph:
4048  case X86::BI__builtin_ia32_vcvtps2ph_mask:
4049  case X86::BI__builtin_ia32_vcvtps2ph256:
4050  case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4051  case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4052  case X86::BI__builtin_ia32_rndscaleps_128_mask:
4053  case X86::BI__builtin_ia32_rndscalepd_128_mask:
4054  case X86::BI__builtin_ia32_rndscaleps_256_mask:
4055  case X86::BI__builtin_ia32_rndscalepd_256_mask:
4056  case X86::BI__builtin_ia32_rndscaleps_mask:
4057  case X86::BI__builtin_ia32_rndscalepd_mask:
4058  case X86::BI__builtin_ia32_reducepd128_mask:
4059  case X86::BI__builtin_ia32_reducepd256_mask:
4060  case X86::BI__builtin_ia32_reducepd512_mask:
4061  case X86::BI__builtin_ia32_reduceps128_mask:
4062  case X86::BI__builtin_ia32_reduceps256_mask:
4063  case X86::BI__builtin_ia32_reduceps512_mask:
4064  case X86::BI__builtin_ia32_prold512:
4065  case X86::BI__builtin_ia32_prolq512:
4066  case X86::BI__builtin_ia32_prold128:
4067  case X86::BI__builtin_ia32_prold256:
4068  case X86::BI__builtin_ia32_prolq128:
4069  case X86::BI__builtin_ia32_prolq256:
4070  case X86::BI__builtin_ia32_prord512:
4071  case X86::BI__builtin_ia32_prorq512:
4072  case X86::BI__builtin_ia32_prord128:
4073  case X86::BI__builtin_ia32_prord256:
4074  case X86::BI__builtin_ia32_prorq128:
4075  case X86::BI__builtin_ia32_prorq256:
4076  case X86::BI__builtin_ia32_fpclasspd128_mask:
4077  case X86::BI__builtin_ia32_fpclasspd256_mask:
4078  case X86::BI__builtin_ia32_fpclassps128_mask:
4079  case X86::BI__builtin_ia32_fpclassps256_mask:
4080  case X86::BI__builtin_ia32_fpclassps512_mask:
4081  case X86::BI__builtin_ia32_fpclasspd512_mask:
4082  case X86::BI__builtin_ia32_fpclasssd_mask:
4083  case X86::BI__builtin_ia32_fpclassss_mask:
4084  case X86::BI__builtin_ia32_pslldqi128_byteshift:
4085  case X86::BI__builtin_ia32_pslldqi256_byteshift:
4086  case X86::BI__builtin_ia32_pslldqi512_byteshift:
4087  case X86::BI__builtin_ia32_psrldqi128_byteshift:
4088  case X86::BI__builtin_ia32_psrldqi256_byteshift:
4089  case X86::BI__builtin_ia32_psrldqi512_byteshift:
4090  case X86::BI__builtin_ia32_kshiftliqi:
4091  case X86::BI__builtin_ia32_kshiftlihi:
4092  case X86::BI__builtin_ia32_kshiftlisi:
4093  case X86::BI__builtin_ia32_kshiftlidi:
4094  case X86::BI__builtin_ia32_kshiftriqi:
4095  case X86::BI__builtin_ia32_kshiftrihi:
4096  case X86::BI__builtin_ia32_kshiftrisi:
4097  case X86::BI__builtin_ia32_kshiftridi:
4098  i = 1; l = 0; u = 255;
4099  break;
4100  case X86::BI__builtin_ia32_vperm2f128_pd256:
4101  case X86::BI__builtin_ia32_vperm2f128_ps256:
4102  case X86::BI__builtin_ia32_vperm2f128_si256:
4103  case X86::BI__builtin_ia32_permti256:
4104  case X86::BI__builtin_ia32_pblendw128:
4105  case X86::BI__builtin_ia32_pblendw256:
4106  case X86::BI__builtin_ia32_blendps256:
4107  case X86::BI__builtin_ia32_pblendd256:
4108  case X86::BI__builtin_ia32_palignr128:
4109  case X86::BI__builtin_ia32_palignr256:
4110  case X86::BI__builtin_ia32_palignr512:
4111  case X86::BI__builtin_ia32_alignq512:
4112  case X86::BI__builtin_ia32_alignd512:
4113  case X86::BI__builtin_ia32_alignd128:
4114  case X86::BI__builtin_ia32_alignd256:
4115  case X86::BI__builtin_ia32_alignq128:
4116  case X86::BI__builtin_ia32_alignq256:
4117  case X86::BI__builtin_ia32_vcomisd:
4118  case X86::BI__builtin_ia32_vcomiss:
4119  case X86::BI__builtin_ia32_shuf_f32x4:
4120  case X86::BI__builtin_ia32_shuf_f64x2:
4121  case X86::BI__builtin_ia32_shuf_i32x4:
4122  case X86::BI__builtin_ia32_shuf_i64x2:
4123  case X86::BI__builtin_ia32_shufpd512:
4124  case X86::BI__builtin_ia32_shufps:
4125  case X86::BI__builtin_ia32_shufps256:
4126  case X86::BI__builtin_ia32_shufps512:
4127  case X86::BI__builtin_ia32_dbpsadbw128:
4128  case X86::BI__builtin_ia32_dbpsadbw256:
4129  case X86::BI__builtin_ia32_dbpsadbw512:
4130  case X86::BI__builtin_ia32_vpshldd128:
4131  case X86::BI__builtin_ia32_vpshldd256:
4132  case X86::BI__builtin_ia32_vpshldd512:
4133  case X86::BI__builtin_ia32_vpshldq128:
4134  case X86::BI__builtin_ia32_vpshldq256:
4135  case X86::BI__builtin_ia32_vpshldq512:
4136  case X86::BI__builtin_ia32_vpshldw128:
4137  case X86::BI__builtin_ia32_vpshldw256:
4138  case X86::BI__builtin_ia32_vpshldw512:
4139  case X86::BI__builtin_ia32_vpshrdd128:
4140  case X86::BI__builtin_ia32_vpshrdd256:
4141  case X86::BI__builtin_ia32_vpshrdd512:
4142  case X86::BI__builtin_ia32_vpshrdq128:
4143  case X86::BI__builtin_ia32_vpshrdq256:
4144  case X86::BI__builtin_ia32_vpshrdq512:
4145  case X86::BI__builtin_ia32_vpshrdw128:
4146  case X86::BI__builtin_ia32_vpshrdw256:
4147  case X86::BI__builtin_ia32_vpshrdw512:
4148  i = 2; l = 0; u = 255;
4149  break;
4150  case X86::BI__builtin_ia32_fixupimmpd512_mask:
4151  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4152  case X86::BI__builtin_ia32_fixupimmps512_mask:
4153  case X86::BI__builtin_ia32_fixupimmps512_maskz:
4154  case X86::BI__builtin_ia32_fixupimmsd_mask:
4155  case X86::BI__builtin_ia32_fixupimmsd_maskz:
4156  case X86::BI__builtin_ia32_fixupimmss_mask:
4157  case X86::BI__builtin_ia32_fixupimmss_maskz:
4158  case X86::BI__builtin_ia32_fixupimmpd128_mask:
4159  case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4160  case X86::BI__builtin_ia32_fixupimmpd256_mask:
4161  case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4162  case X86::BI__builtin_ia32_fixupimmps128_mask:
4163  case X86::BI__builtin_ia32_fixupimmps128_maskz:
4164  case X86::BI__builtin_ia32_fixupimmps256_mask:
4165  case X86::BI__builtin_ia32_fixupimmps256_maskz:
4166  case X86::BI__builtin_ia32_pternlogd512_mask:
4167  case X86::BI__builtin_ia32_pternlogd512_maskz:
4168  case X86::BI__builtin_ia32_pternlogq512_mask:
4169  case X86::BI__builtin_ia32_pternlogq512_maskz:
4170  case X86::BI__builtin_ia32_pternlogd128_mask:
4171  case X86::BI__builtin_ia32_pternlogd128_maskz:
4172  case X86::BI__builtin_ia32_pternlogd256_mask:
4173  case X86::BI__builtin_ia32_pternlogd256_maskz:
4174  case X86::BI__builtin_ia32_pternlogq128_mask:
4175  case X86::BI__builtin_ia32_pternlogq128_maskz:
4176  case X86::BI__builtin_ia32_pternlogq256_mask:
4177  case X86::BI__builtin_ia32_pternlogq256_maskz:
4178  i = 3; l = 0; u = 255;
4179  break;
4180  case X86::BI__builtin_ia32_gatherpfdpd:
4181  case X86::BI__builtin_ia32_gatherpfdps:
4182  case X86::BI__builtin_ia32_gatherpfqpd:
4183  case X86::BI__builtin_ia32_gatherpfqps:
4184  case X86::BI__builtin_ia32_scatterpfdpd:
4185  case X86::BI__builtin_ia32_scatterpfdps:
4186  case X86::BI__builtin_ia32_scatterpfqpd:
4187  case X86::BI__builtin_ia32_scatterpfqps:
4188  i = 4; l = 2; u = 3;
4189  break;
4190  case X86::BI__builtin_ia32_reducesd_mask:
4191  case X86::BI__builtin_ia32_reducess_mask:
4192  case X86::BI__builtin_ia32_rndscalesd_round_mask:
4193  case X86::BI__builtin_ia32_rndscaless_round_mask:
4194  i = 4; l = 0; u = 255;
4195  break;
4196  }
4197 
4198  // Note that we don't force a hard error on the range check here, allowing
4199  // template-generated or macro-generated dead code to potentially have out-of-
4200  // range values. These need to code generate, but don't need to necessarily
4201  // make any sense. We use a warning that defaults to an error.
4202  return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4203 }
4204 
4205 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4206 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4207 /// Returns true when the format fits the function and the FormatStringInfo has
4208 /// been populated.
4209 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4210  FormatStringInfo *FSI) {
4211  FSI->HasVAListArg = Format->getFirstArg() == 0;
4212  FSI->FormatIdx = Format->getFormatIdx() - 1;
4213  FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4214 
4215  // The way the format attribute works in GCC, the implicit this argument
4216  // of member functions is counted. However, it doesn't appear in our own
4217  // lists, so decrement format_idx in that case.
4218  if (IsCXXMember) {
4219  if(FSI->FormatIdx == 0)
4220  return false;
4221  --FSI->FormatIdx;
4222  if (FSI->FirstDataArg != 0)
4223  --FSI->FirstDataArg;
4224  }
4225  return true;
4226 }
4227 
4228 /// Checks if a the given expression evaluates to null.
4229 ///
4230 /// Returns true if the value evaluates to null.
4231 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4232  // If the expression has non-null type, it doesn't evaluate to null.
4233  if (auto nullability
4234  = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4235  if (*nullability == NullabilityKind::NonNull)
4236  return false;
4237  }
4238 
4239  // As a special case, transparent unions initialized with zero are
4240  // considered null for the purposes of the nonnull attribute.
4241  if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4242  if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4243  if (const CompoundLiteralExpr *CLE =
4244  dyn_cast<CompoundLiteralExpr>(Expr))
4245  if (const InitListExpr *ILE =
4246  dyn_cast<InitListExpr>(CLE->getInitializer()))
4247  Expr = ILE->getInit(0);
4248  }
4249 
4250  bool Result;
4251  return (!Expr->isValueDependent() &&
4252  Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4253  !Result);
4254 }
4255 
4257  const Expr *ArgExpr,
4258  SourceLocation CallSiteLoc) {
4259  if (CheckNonNullExpr(S, ArgExpr))
4260  S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4261  S.PDiag(diag::warn_null_arg)
4262  << ArgExpr->getSourceRange());
4263 }
4264 
4265 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4266  FormatStringInfo FSI;
4267  if ((GetFormatStringType(Format) == FST_NSString) &&
4268  getFormatStringInfo(Format, false, &FSI)) {
4269  Idx = FSI.FormatIdx;
4270  return true;
4271  }
4272  return false;
4273 }
4274 
4275 /// Diagnose use of %s directive in an NSString which is being passed
4276 /// as formatting string to formatting method.
4277 static void
4279  const NamedDecl *FDecl,
4280  Expr **Args,
4281  unsigned NumArgs) {
4282  unsigned Idx = 0;
4283  bool Format = false;
4285  if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4286  Idx = 2;
4287  Format = true;
4288  }
4289  else
4290  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4291  if (S.GetFormatNSStringIdx(I, Idx)) {
4292  Format = true;
4293  break;
4294  }
4295  }
4296  if (!Format || NumArgs <= Idx)
4297  return;
4298  const Expr *FormatExpr = Args[Idx];
4299  if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4300  FormatExpr = CSCE->getSubExpr();
4301  const StringLiteral *FormatString;
4302  if (const ObjCStringLiteral *OSL =
4303  dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4304  FormatString = OSL->getString();
4305  else
4306  FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4307  if (!FormatString)
4308  return;
4309  if (S.FormatStringHasSArg(FormatString)) {
4310  S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4311  << "%s" << 1 << 1;
4312  S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4313  << FDecl->getDeclName();
4314  }
4315 }
4316 
4317 /// Determine whether the given type has a non-null nullability annotation.
4319  if (auto nullability = type->getNullability(ctx))
4320  return *nullability == NullabilityKind::NonNull;
4321 
4322  return false;
4323 }
4324 
4326  const NamedDecl *FDecl,
4327  const FunctionProtoType *Proto,
4328  ArrayRef<const Expr *> Args,
4329  SourceLocation CallSiteLoc) {
4330  assert((FDecl || Proto) && "Need a function declaration or prototype");
4331 
4332  // Already checked by by constant evaluator.
4333  if (S.isConstantEvaluated())
4334  return;
4335  // Check the attributes attached to the method/function itself.
4336  llvm::SmallBitVector NonNullArgs;
4337  if (FDecl) {
4338  // Handle the nonnull attribute on the function/method declaration itself.
4339  for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4340  if (!NonNull->args_size()) {
4341  // Easy case: all pointer arguments are nonnull.
4342  for (const auto *Arg : Args)
4343  if (S.isValidPointerAttrType(Arg->getType()))
4344  CheckNonNullArgument(S, Arg, CallSiteLoc);
4345  return;
4346  }
4347 
4348  for (const ParamIdx &Idx : NonNull->args()) {
4349  unsigned IdxAST = Idx.getASTIndex();
4350  if (IdxAST >= Args.size())
4351  continue;
4352  if (NonNullArgs.empty())
4353  NonNullArgs.resize(Args.size());
4354  NonNullArgs.set(IdxAST);
4355  }
4356  }
4357  }
4358 
4359  if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4360  // Handle the nonnull attribute on the parameters of the
4361  // function/method.
4362  ArrayRef<ParmVarDecl*> parms;
4363  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4364  parms = FD->parameters();
4365  else
4366  parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4367 
4368  unsigned ParamIndex = 0;
4369  for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4370  I != E; ++I, ++ParamIndex) {
4371  const ParmVarDecl *PVD = *I;
4372  if (PVD->hasAttr<NonNullAttr>() ||
4373  isNonNullType(S.Context, PVD->getType())) {
4374  if (NonNullArgs.empty())
4375  NonNullArgs.resize(Args.size());
4376 
4377  NonNullArgs.set(ParamIndex);
4378  }
4379  }
4380  } else {
4381  // If we have a non-function, non-method declaration but no
4382  // function prototype, try to dig out the function prototype.
4383  if (!Proto) {
4384  if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4385  QualType type = VD->getType().getNonReferenceType();
4386  if (auto pointerType = type->getAs<PointerType>())
4387  type = pointerType->getPointeeType();
4388  else if (auto blockType = type->getAs<BlockPointerType>())
4389  type = blockType->getPointeeType();
4390  // FIXME: data member pointers?
4391 
4392  // Dig out the function prototype, if there is one.
4393  Proto = type->getAs<FunctionProtoType>();
4394  }
4395  }
4396 
4397  // Fill in non-null argument information from the nullability
4398  // information on the parameter types (if we have them).
4399  if (Proto) {
4400  unsigned Index = 0;
4401  for (auto paramType : Proto->getParamTypes()) {
4402  if (isNonNullType(S.Context, paramType)) {
4403  if (NonNullArgs.empty())
4404  NonNullArgs.resize(Args.size());
4405 
4406  NonNullArgs.set(Index);
4407  }
4408 
4409  ++Index;
4410  }
4411  }
4412  }
4413 
4414  // Check for non-null arguments.
4415  for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4416  ArgIndex != ArgIndexEnd; ++ArgIndex) {
4417  if (NonNullArgs[ArgIndex])
4418  CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4419  }
4420 }
4421 
4422 /// Handles the checks for format strings, non-POD arguments to vararg
4423 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4424 /// attributes.
4425 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4426  const Expr *ThisArg, ArrayRef<const Expr *> Args,
4427  bool IsMemberFunction, SourceLocation Loc,
4428  SourceRange Range, VariadicCallType CallType) {
4429  // FIXME: We should check as much as we can in the template definition.
4430  if (CurContext->isDependentContext())
4431  return;
4432 
4433  // Printf and scanf checking.
4434  llvm::SmallBitVector CheckedVarArgs;
4435  if (FDecl) {
4436  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4437  // Only create vector if there are format attributes.
4438  CheckedVarArgs.resize(Args.size());
4439 
4440  CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4441  CheckedVarArgs);
4442  }
4443  }
4444 
4445  // Refuse POD arguments that weren't caught by the format string
4446  // checks above.
4447  auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4448  if (CallType != VariadicDoesNotApply &&
4449  (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4450  unsigned NumParams = Proto ? Proto->getNumParams()
4451  : FDecl && isa<FunctionDecl>(FDecl)
4452  ? cast<FunctionDecl>(FDecl)->getNumParams()
4453  : FDecl && isa<ObjCMethodDecl>(FDecl)
4454  ? cast<ObjCMethodDecl>(FDecl)->param_size()
4455  : 0;
4456 
4457  for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4458  // Args[ArgIdx] can be null in malformed code.
4459  if (const Expr *Arg = Args[ArgIdx]) {
4460  if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4461  checkVariadicArgument(Arg, CallType);
4462  }
4463  }
4464  }
4465 
4466  if (FDecl || Proto) {
4467  CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4468 
4469  // Type safety checking.
4470  if (FDecl) {
4471  for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4472  CheckArgumentWithTypeTag(I, Args, Loc);
4473  }
4474  }
4475 
4476  if (FD)
4477  diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4478 }
4479 
4480 /// CheckConstructorCall - Check a constructor call for correctness and safety
4481 /// properties not enforced by the C type system.
4482 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4483  ArrayRef<const Expr *> Args,
4484  const FunctionProtoType *Proto,
4485  SourceLocation Loc) {
4486  VariadicCallType CallType =
4487  Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4488  checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4489  Loc, SourceRange(), CallType);
4490 }
4491 
4492 /// CheckFunctionCall - Check a direct function call for various correctness
4493 /// and safety properties not strictly enforced by the C type system.
4494 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4495  const FunctionProtoType *Proto) {
4496  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4497  isa<CXXMethodDecl>(FDecl);
4498  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4499  IsMemberOperatorCall;
4500  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4501  TheCall->getCallee());
4502  Expr** Args = TheCall->getArgs();
4503  unsigned NumArgs = TheCall->getNumArgs();
4504 
4505  Expr *ImplicitThis = nullptr;
4506  if (IsMemberOperatorCall) {
4507  // If this is a call to a member operator, hide the first argument
4508  // from checkCall.
4509  // FIXME: Our choice of AST representation here is less than ideal.
4510  ImplicitThis = Args[0];
4511  ++Args;
4512  --NumArgs;
4513  } else if (IsMemberFunction)
4514  ImplicitThis =
4515  cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4516 
4517  checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4518  IsMemberFunction, TheCall->getRParenLoc(),
4519  TheCall->getCallee()->getSourceRange(), CallType);
4520 
4521  IdentifierInfo *FnInfo = FDecl->getIdentifier();
4522  // None of the checks below are needed for functions that don't have
4523  // simple names (e.g., C++ conversion functions).
4524  if (!FnInfo)
4525  return false;
4526 
4527  CheckAbsoluteValueFunction(TheCall, FDecl);
4528  CheckMaxUnsignedZero(TheCall, FDecl);
4529 
4530  if (getLangOpts().ObjC)
4531  DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4532 
4533  unsigned CMId = FDecl->getMemoryFunctionKind();
4534  if (CMId == 0)
4535  return false;
4536 
4537  // Handle memory setting and copying functions.
4538  if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4539  CheckStrlcpycatArguments(TheCall, FnInfo);
4540  else if (CMId == Builtin::BIstrncat)
4541  CheckStrncatArguments(TheCall, FnInfo);
4542  else
4543  CheckMemaccessArguments(TheCall, CMId, FnInfo);
4544 
4545  return false;
4546 }
4547 
4548 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4549  ArrayRef<const Expr *> Args) {
4550  VariadicCallType CallType =
4551  Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4552 
4553  checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4554  /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4555  CallType);
4556 
4557  return false;
4558 }
4559 
4560 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4561  const FunctionProtoType *Proto) {
4562  QualType Ty;
4563  if (const auto *V = dyn_cast<VarDecl>(NDecl))
4564  Ty = V->getType().getNonReferenceType();
4565  else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4566  Ty = F->getType().getNonReferenceType();
4567  else
4568  return false;
4569 
4570  if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4571  !Ty->isFunctionProtoType())
4572  return false;
4573 
4574  VariadicCallType CallType;
4575  if (!Proto || !Proto->isVariadic()) {
4576  CallType = VariadicDoesNotApply;
4577  } else if (Ty->isBlockPointerType()) {
4578  CallType = VariadicBlock;
4579  } else { // Ty->isFunctionPointerType()
4580  CallType = VariadicFunction;
4581  }
4582 
4583  checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4584  llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4585  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4586  TheCall->getCallee()->getSourceRange(), CallType);
4587 
4588  return false;
4589 }
4590 
4591 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4592 /// such as function pointers returned from functions.
4593 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4594  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4595  TheCall->getCallee());
4596  checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4597  llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4598  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4599  TheCall->getCallee()->getSourceRange(), CallType);
4600 
4601  return false;
4602 }
4603 
4604 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4605  if (!llvm::isValidAtomicOrderingCABI(Ordering))
4606  return false;
4607 
4608  auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4609  switch (Op) {
4610  case AtomicExpr::AO__c11_atomic_init:
4611  case AtomicExpr::AO__opencl_atomic_init:
4612  llvm_unreachable("There is no ordering argument for an init");
4613 
4614  case AtomicExpr::AO__c11_atomic_load:
4615  case AtomicExpr::AO__opencl_atomic_load:
4616  case AtomicExpr::AO__atomic_load_n:
4617  case AtomicExpr::AO__atomic_load:
4618  return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4619  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4620 
4621  case AtomicExpr::AO__c11_atomic_store:
4622  case AtomicExpr::AO__opencl_atomic_store:
4623  case AtomicExpr::AO__atomic_store:
4624  case AtomicExpr::AO__atomic_store_n:
4625  return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4626  OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4627  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4628 
4629  default:
4630  return true;
4631  }
4632 }
4633 
4634 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4635  AtomicExpr::AtomicOp Op) {
4636  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4637  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4638  MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4639  return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4640  DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4641  Op);
4642 }
4643 
4645  SourceLocation RParenLoc, MultiExprArg Args,
4647  AtomicArgumentOrder ArgOrder) {
4648  // All the non-OpenCL operations take one of the following forms.
4649  // The OpenCL operations take the __c11 forms with one extra argument for
4650  // synchronization scope.
4651  enum {
4652  // C __c11_atomic_init(A *, C)
4653  Init,
4654 
4655  // C __c11_atomic_load(A *, int)
4656  Load,
4657 
4658  // void __atomic_load(A *, CP, int)
4659  LoadCopy,
4660 
4661  // void __atomic_store(A *, CP, int)
4662  Copy,
4663 
4664  // C __c11_atomic_add(A *, M, int)
4665  Arithmetic,
4666 
4667  // C __atomic_exchange_n(A *, CP, int)
4668  Xchg,
4669 
4670  // void __atomic_exchange(A *, C *, CP, int)
4671  GNUXchg,
4672 
4673  // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4674  C11CmpXchg,
4675 
4676  // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4677  GNUCmpXchg
4678  } Form = Init;
4679 
4680  const unsigned NumForm = GNUCmpXchg + 1;
4681  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4682  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4683  // where:
4684  // C is an appropriate type,
4685  // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4686  // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4687  // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4688  // the int parameters are for orderings.
4689 
4690  static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4691  && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4692  "need to update code for modified forms");
4693  static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4694  AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4695  AtomicExpr::AO__atomic_load,
4696  "need to update code for modified C11 atomics");
4697  bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4698  Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4699  bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4700  Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4701  IsOpenCL;
4702  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4703  Op == AtomicExpr::AO__atomic_store_n ||
4704  Op == AtomicExpr::AO__atomic_exchange_n ||
4705  Op == AtomicExpr::AO__atomic_compare_exchange_n;
4706  bool IsAddSub = false;
4707 
4708  switch (Op) {
4709  case AtomicExpr::AO__c11_atomic_init:
4710  case AtomicExpr::AO__opencl_atomic_init:
4711  Form = Init;
4712  break;
4713 
4714  case AtomicExpr::AO__c11_atomic_load:
4715  case AtomicExpr::AO__opencl_atomic_load:
4716  case AtomicExpr::AO__atomic_load_n:
4717  Form = Load;
4718  break;
4719 
4720  case AtomicExpr::AO__atomic_load:
4721  Form = LoadCopy;
4722  break;
4723 
4724  case AtomicExpr::AO__c11_atomic_store:
4725  case AtomicExpr::AO__opencl_atomic_store:
4726  case AtomicExpr::AO__atomic_store:
4727  case AtomicExpr::AO__atomic_store_n:
4728  Form = Copy;
4729  break;
4730 
4731  case AtomicExpr::AO__c11_atomic_fetch_add:
4732  case AtomicExpr::AO__c11_atomic_fetch_sub:
4733  case AtomicExpr::AO__opencl_atomic_fetch_add:
4734  case AtomicExpr::AO__opencl_atomic_fetch_sub:
4735  case AtomicExpr::AO__atomic_fetch_add:
4736  case AtomicExpr::AO__atomic_fetch_sub:
4737  case AtomicExpr::AO__atomic_add_fetch:
4738  case AtomicExpr::AO__atomic_sub_fetch:
4739  IsAddSub = true;
4740  LLVM_FALLTHROUGH;
4741  case AtomicExpr::AO__c11_atomic_fetch_and:
4742  case AtomicExpr::AO__c11_atomic_fetch_or:
4743  case AtomicExpr::AO__c11_atomic_fetch_xor:
4744  case AtomicExpr::AO__opencl_atomic_fetch_and:
4745  case AtomicExpr::AO__opencl_atomic_fetch_or:
4746  case AtomicExpr::AO__opencl_atomic_fetch_xor:
4747  case AtomicExpr::AO__atomic_fetch_and:
4748  case AtomicExpr::AO__atomic_fetch_or:
4749  case AtomicExpr::AO__atomic_fetch_xor:
4750  case AtomicExpr::AO__atomic_fetch_nand:
4751  case AtomicExpr::AO__atomic_and_fetch:
4752  case AtomicExpr::AO__atomic_or_fetch:
4753  case AtomicExpr::AO__atomic_xor_fetch:
4754  case AtomicExpr::AO__atomic_nand_fetch:
4755  case AtomicExpr::AO__c11_atomic_fetch_min:
4756  case AtomicExpr::AO__c11_atomic_fetch_max:
4757  case AtomicExpr::AO__opencl_atomic_fetch_min:
4758  case AtomicExpr::AO__opencl_atomic_fetch_max:
4759  case AtomicExpr::AO__atomic_min_fetch:
4760  case AtomicExpr::AO__atomic_max_fetch:
4761  case AtomicExpr::AO__atomic_fetch_min:
4762  case AtomicExpr::AO__atomic_fetch_max:
4763  Form = Arithmetic;
4764  break;
4765 
4766  case AtomicExpr::AO__c11_atomic_exchange:
4767  case AtomicExpr::AO__opencl_atomic_exchange:
4768  case AtomicExpr::AO__atomic_exchange_n:
4769  Form = Xchg;
4770  break;
4771 
4772  case AtomicExpr::AO__atomic_exchange:
4773  Form = GNUXchg;
4774  break;
4775 
4776  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4777  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4778  case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4779  case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4780  Form = C11CmpXchg;
4781  break;
4782 
4783  case AtomicExpr::AO__atomic_compare_exchange:
4784  case AtomicExpr::AO__atomic_compare_exchange_n:
4785  Form = GNUCmpXchg;
4786  break;
4787  }
4788 
4789  unsigned AdjustedNumArgs = NumArgs[Form];
4790  if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4791  ++AdjustedNumArgs;
4792  // Check we have the right number of arguments.
4793  if (Args.size() < AdjustedNumArgs) {
4794  Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4795  << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4796  << ExprRange;
4797  return ExprError();
4798  } else if (Args.size() > AdjustedNumArgs) {
4799  Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4800  diag::err_typecheck_call_too_many_args)
4801  << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4802  << ExprRange;
4803  return ExprError();
4804  }
4805 
4806  // Inspect the first argument of the atomic operation.
4807  Expr *Ptr = Args[0];
4808  ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4809  if (ConvertedPtr.isInvalid())
4810  return ExprError();
4811 
4812  Ptr = ConvertedPtr.get();
4813  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4814  if (!pointerType) {
4815  Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4816  << Ptr->getType() << Ptr->getSourceRange();
4817  return ExprError();
4818  }
4819 
4820  // For a __c11 builtin, this should be a pointer to an _Atomic type.
4821  QualType AtomTy = pointerType->getPointeeType(); // 'A'
4822  QualType ValType = AtomTy; // 'C'
4823  if (IsC11) {
4824  if (!AtomTy->isAtomicType()) {
4825  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4826  << Ptr->getType() << Ptr->getSourceRange();
4827  return ExprError();
4828  }
4829  if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4831  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4832  << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4833  << Ptr->getSourceRange();
4834  return ExprError();
4835  }
4836  ValType = AtomTy->castAs<AtomicType>()->getValueType();
4837  } else if (Form != Load && Form != LoadCopy) {
4838  if (ValType.isConstQualified()) {
4839  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4840  << Ptr->getType() << Ptr->getSourceRange();
4841  return ExprError();
4842  }
4843  }
4844 
4845  // For an arithmetic operation, the implied arithmetic must be well-formed.
4846  if (Form == Arithmetic) {
4847  // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4848  if (IsAddSub && !ValType->isIntegerType()
4849  && !ValType->isPointerType()) {
4850  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4851  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4852  return ExprError();
4853  }
4854  if (!IsAddSub && !ValType->isIntegerType()) {
4855  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4856  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4857  return ExprError();
4858  }
4859  if (IsC11 && ValType->isPointerType() &&
4860  RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4861  diag::err_incomplete_type)) {
4862  return ExprError();
4863  }
4864  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4865  // For __atomic_*_n operations, the value type must be a scalar integral or
4866  // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4867  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4868  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4869  return ExprError();
4870  }
4871 
4872  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4873  !AtomTy->isScalarType()) {
4874  // For GNU atomics, require a trivially-copyable type. This is not part of
4875  // the GNU atomics specification, but we enforce it for sanity.
4876  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4877  << Ptr->getType() << Ptr->getSourceRange();
4878  return ExprError();
4879  }
4880 
4881  switch (ValType.getObjCLifetime()) {
4882  case Qualifiers::OCL_None:
4884  // okay
4885  break;
4886 
4887  case Qualifiers::OCL_Weak:
4890  // FIXME: Can this happen? By this point, ValType should be known
4891  // to be trivially copyable.
4892  Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4893  << ValType << Ptr->getSourceRange();
4894  return ExprError();
4895  }
4896 
4897  // All atomic operations have an overload which takes a pointer to a volatile
4898  // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4899  // into the result or the other operands. Similarly atomic_load takes a
4900  // pointer to a const 'A'.
4901  ValType.removeLocalVolatile();
4902  ValType.removeLocalConst();
4903  QualType ResultType = ValType;
4904  if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4905  Form == Init)
4906  ResultType = Context.VoidTy;
4907  else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4908  ResultType = Context.BoolTy;
4909 
4910  // The type of a parameter passed 'by value'. In the GNU atomics, such
4911  // arguments are actually passed as pointers.
4912  QualType ByValType = ValType; // 'CP'
4913  bool IsPassedByAddress = false;
4914  if (!IsC11 && !IsN) {
4915  ByValType = Ptr->getType();
4916  IsPassedByAddress = true;
4917  }
4918 
4919  SmallVector<Expr *, 5> APIOrderedArgs;
4920  if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4921  APIOrderedArgs.push_back(Args[0]);
4922  switch (Form) {
4923  case Init:
4924  case Load:
4925  APIOrderedArgs.push_back(Args[1]); // Val1/Order
4926  break;
4927  case LoadCopy:
4928  case Copy:
4929  case Arithmetic:
4930  case Xchg:
4931  APIOrderedArgs.push_back(Args[2]); // Val1
4932  APIOrderedArgs.push_back(Args[1]); // Order
4933  break;
4934  case GNUXchg:
4935  APIOrderedArgs.push_back(Args[2]); // Val1
4936  APIOrderedArgs.push_back(Args[3]); // Val2
4937  APIOrderedArgs.push_back(Args[1]); // Order
4938  break;
4939  case C11CmpXchg:
4940  APIOrderedArgs.push_back(Args[2]); // Val1
4941  APIOrderedArgs.push_back(Args[4]); // Val2
4942  APIOrderedArgs.push_back(Args[1]); // Order
4943  APIOrderedArgs.push_back(Args[3]); // OrderFail
4944  break;
4945  case GNUCmpXchg:
4946  APIOrderedArgs.push_back(Args[2]); // Val1
4947  APIOrderedArgs.push_back(Args[4]); // Val2
4948  APIOrderedArgs.push_back(Args[5]); // Weak
4949  APIOrderedArgs.push_back(Args[1]); // Order
4950  APIOrderedArgs.push_back(Args[3]); // OrderFail
4951  break;
4952  }
4953  } else
4954  APIOrderedArgs.append(Args.begin(), Args.end());
4955 
4956  // The first argument's non-CV pointer type is used to deduce the type of
4957  // subsequent arguments, except for:
4958  // - weak flag (always converted to bool)
4959  // - memory order (always converted to int)
4960  // - scope (always converted to int)
4961  for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4962  QualType Ty;
4963  if (i < NumVals[Form] + 1) {
4964  switch (i) {
4965  case 0:
4966  // The first argument is always a pointer. It has a fixed type.
4967  // It is always dereferenced, a nullptr is undefined.
4968  CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4969  // Nothing else to do: we already know all we want about this pointer.
4970  continue;
4971  case 1:
4972  // The second argument is the non-atomic operand. For arithmetic, this
4973  // is always passed by value, and for a compare_exchange it is always
4974  // passed by address. For the rest, GNU uses by-address and C11 uses
4975  // by-value.
4976  assert(Form != Load);
4977  if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4978  Ty = ValType;
4979  else if (Form == Copy || Form == Xchg) {
4980  if (IsPassedByAddress) {
4981  // The value pointer is always dereferenced, a nullptr is undefined.
4982  CheckNonNullArgument(*this, APIOrderedArgs[i],
4983  ExprRange.getBegin());
4984  }
4985  Ty = ByValType;
4986  } else if (Form == Arithmetic)
4987  Ty = Context.getPointerDiffType();
4988  else {
4989  Expr *ValArg = APIOrderedArgs[i];
4990  // The value pointer is always dereferenced, a nullptr is undefined.
4991  CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4992  LangAS AS = LangAS::Default;
4993  // Keep address space of non-atomic pointer type.
4994  if (const PointerType *PtrTy =
4995  ValArg->getType()->getAs<PointerType>()) {
4996  AS = PtrTy->getPointeeType().getAddressSpace();
4997  }
4998  Ty = Context.getPointerType(
4999  Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5000  }
5001  break;
5002  case 2:
5003  // The third argument to compare_exchange / GNU exchange is the desired
5004  // value, either by-value (for the C11 and *_n variant) or as a pointer.
5005  if (IsPassedByAddress)
5006  CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5007  Ty = ByValType;
5008  break;
5009  case 3:
5010  // The fourth argument to GNU compare_exchange is a 'weak' flag.
5011  Ty = Context.BoolTy;
5012  break;
5013  }
5014  } else {
5015  // The order(s) and scope are always converted to int.
5016  Ty = Context.IntTy;
5017  }
5018 
5019  InitializedEntity Entity =
5020  InitializedEntity::InitializeParameter(Context, Ty, false);
5021  ExprResult Arg = APIOrderedArgs[i];
5022  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5023  if (Arg.isInvalid())
5024  return true;
5025  APIOrderedArgs[i] = Arg.get();
5026  }
5027 
5028  // Permute the arguments into a 'consistent' order.
5029  SmallVector<Expr*, 5> SubExprs;
5030  SubExprs.push_back(Ptr);
5031  switch (Form) {
5032  case Init:
5033  // Note, AtomicExpr::getVal1() has a special case for this atomic.
5034  SubExprs.push_back(APIOrderedArgs[1]); // Val1
5035  break;
5036  case Load:
5037  SubExprs.push_back(APIOrderedArgs[1]); // Order
5038  break;
5039  case LoadCopy:
5040  case Copy:
5041  case Arithmetic:
5042  case Xchg:
5043  SubExprs.push_back(APIOrderedArgs[2]); // Order
5044  SubExprs.push_back(APIOrderedArgs[1]); // Val1
5045  break;
5046  case GNUXchg:
5047  // Note, AtomicExpr::getVal2() has a special case for this atomic.
5048  SubExprs.push_back(APIOrderedArgs[3]); // Order
5049  SubExprs.push_back(APIOrderedArgs[1]); // Val1
5050  SubExprs.push_back(APIOrderedArgs[2]); // Val2
5051  break;
5052  case C11CmpXchg:
5053  SubExprs.push_back(APIOrderedArgs[3]); // Order
5054  SubExprs.push_back(APIOrderedArgs[1]); // Val1
5055  SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5056  SubExprs.push_back(APIOrderedArgs[2]); // Val2
5057  break;
5058  case GNUCmpXchg:
5059  SubExprs.push_back(APIOrderedArgs[4]); // Order
5060  SubExprs.push_back(APIOrderedArgs[1]); // Val1
5061  SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5062  SubExprs.push_back(APIOrderedArgs[2]); // Val2
5063  SubExprs.push_back(APIOrderedArgs[3]); // Weak
5064  break;
5065  }
5066 
5067  if (SubExprs.size() >= 2 && Form != Init) {
5068  llvm::APSInt Result(32);
5069  if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
5070  !isValidOrderingForOp(Result.getSExtValue(), Op))
5071  Diag(SubExprs[1]->getBeginLoc(),
5072  diag::warn_atomic_op_has_invalid_memory_order)
5073  << SubExprs[1]->getSourceRange();
5074  }
5075 
5076  if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5077  auto *Scope = Args[Args.size() - 1];
5078  llvm::APSInt Result(32);
5079  if (Scope->isIntegerConstantExpr(Result, Context) &&
5080  !ScopeModel->isValid(Result.getZExtValue())) {
5081  Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5082  << Scope->getSourceRange();
5083  }
5084  SubExprs.push_back(Scope);
5085  }
5086 
5087  AtomicExpr *AE = new (Context)
5088  AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5089 
5090  if ((Op == AtomicExpr::AO__c11_atomic_load ||
5091  Op == AtomicExpr::AO__c11_atomic_store ||
5092  Op == AtomicExpr::AO__opencl_atomic_load ||
5093  Op == AtomicExpr::AO__opencl_atomic_store ) &&
5094  Context.AtomicUsesUnsupportedLibcall(AE))
5095  Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5096  << ((Op == AtomicExpr::AO__c11_atomic_load ||
5097  Op == AtomicExpr::AO__opencl_atomic_load)
5098  ? 0
5099  : 1);
5100 
5101  return AE;
5102 }
5103 
5104 /// checkBuiltinArgument - Given a call to a builtin function, perform
5105 /// normal type-checking on the given argument, updating the call in
5106 /// place. This is useful when a builtin function requires custom
5107 /// type-checking for some of its arguments but not necessarily all of
5108 /// them.
5109 ///
5110 /// Returns true on error.
5111 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5112  FunctionDecl *Fn = E->getDirectCallee();
5113  assert(Fn && "builtin call without direct callee!");
5114 
5115  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5116  InitializedEntity Entity =
5118 
5119  ExprResult Arg = E->getArg(0);
5120  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5121  if (Arg.isInvalid())
5122  return true;
5123 
5124  E->setArg(ArgIndex, Arg.get());
5125  return false;
5126 }
5127 
5128 /// We have a call to a function like __sync_fetch_and_add, which is an
5129 /// overloaded function based on the pointer type of its first argument.
5130 /// The main BuildCallExpr routines have already promoted the types of
5131 /// arguments because all of these calls are prototyped as void(...).
5132 ///
5133 /// This function goes through and does final semantic checking for these
5134 /// builtins, as well as generating any warnings.
5135 ExprResult
5136 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5137  CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5138  Expr *Callee = TheCall->getCallee();
5139  DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5140  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5141 
5142  // Ensure that we have at least one argument to do type inference from.
5143  if (TheCall->getNumArgs() < 1) {
5144  Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5145  << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5146  return ExprError();
5147  }
5148 
5149  // Inspect the first argument of the atomic builtin. This should always be
5150  // a pointer type, whose element is an integral scalar or pointer type.
5151  // Because it is a pointer type, we don't have to worry about any implicit
5152  // casts here.
5153  // FIXME: We don't allow floating point scalars as input.
5154  Expr *FirstArg = TheCall->getArg(0);
5155  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5156  if (FirstArgResult.isInvalid())
5157  return ExprError();
5158  FirstArg = FirstArgResult.get();
5159  TheCall->setArg(0, FirstArg);
5160 
5161  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5162  if (!pointerType) {
5163  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5164  << FirstArg->getType() << FirstArg->getSourceRange();
5165  return ExprError();
5166  }
5167 
5168  QualType ValType = pointerType->getPointeeType();
5169  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5170  !ValType->isBlockPointerType()) {
5171  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5172  << FirstArg->getType() << FirstArg->getSourceRange();
5173  return ExprError();
5174  }
5175 
5176  if (ValType.isConstQualified()) {
5177  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5178  << FirstArg->getType() << FirstArg->getSourceRange();
5179  return ExprError();
5180  }
5181 
5182  switch (ValType.getObjCLifetime()) {
5183  case Qualifiers::OCL_None:
5185  // okay
5186  break;
5187 
5188  case Qualifiers::OCL_Weak:
5191  Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5192  << ValType << FirstArg->getSourceRange();
5193  return ExprError();
5194  }
5195 
5196  // Strip any qualifiers off ValType.
5197  ValType = ValType.getUnqualifiedType();
5198 
5199  // The majority of builtins return a value, but a few have special return
5200  // types, so allow them to override appropriately below.
5201  QualType ResultType = ValType;
5202 
5203  // We need to figure out which concrete builtin this maps onto. For example,
5204  // __sync_fetch_and_add with a 2 byte object turns into
5205  // __sync_fetch_and_add_2.
5206 #define BUILTIN_ROW(x) \
5207  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5208  Builtin::BI##x##_8, Builtin::BI##x##_16 }
5209 
5210  static const unsigned BuiltinIndices[][5] = {
5211  BUILTIN_ROW(__sync_fetch_and_add),
5212  BUILTIN_ROW(__sync_fetch_and_sub),
5213  BUILTIN_ROW(__sync_fetch_and_or),
5214  BUILTIN_ROW(__sync_fetch_and_and),
5215  BUILTIN_ROW(__sync_fetch_and_xor),
5216  BUILTIN_ROW(__sync_fetch_and_nand),
5217 
5218  BUILTIN_ROW(__sync_add_and_fetch),
5219  BUILTIN_ROW(__sync_sub_and_fetch),
5220  BUILTIN_ROW(__sync_and_and_fetch),
5221  BUILTIN_ROW(__sync_or_and_fetch),
5222  BUILTIN_ROW(__sync_xor_and_fetch),
5223  BUILTIN_ROW(__sync_nand_and_fetch),
5224 
5225  BUILTIN_ROW(__sync_val_compare_and_swap),
5226  BUILTIN_ROW(__sync_bool_compare_and_swap),
5227  BUILTIN_ROW(__sync_lock_test_and_set),
5228  BUILTIN_ROW(__sync_lock_release),
5229  BUILTIN_ROW(__sync_swap)
5230  };
5231 #undef BUILTIN_ROW
5232 
5233  // Determine the index of the size.
5234  unsigned SizeIndex;
5235  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5236  case 1: SizeIndex = 0; break;
5237  case 2: SizeIndex = 1; break;
5238  case 4: SizeIndex = 2; break;
5239  case 8: SizeIndex = 3; break;
5240  case 16: SizeIndex = 4; break;
5241  default:
5242  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5243  << FirstArg->getType() << FirstArg->getSourceRange();
5244  return ExprError();
5245  }
5246 
5247  // Each of these builtins has one pointer argument, followed by some number of
5248  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5249  // that we ignore. Find out which row of BuiltinIndices to read from as well
5250  // as the number of fixed args.
5251  unsigned BuiltinID = FDecl->getBuiltinID();
5252  unsigned BuiltinIndex, NumFixed = 1;
5253  bool WarnAboutSemanticsChange = false;
5254  switch (BuiltinID) {
5255  default: llvm_unreachable("Unknown overloaded atomic builtin!");
5256  case Builtin::BI__sync_fetch_and_add:
5257  case Builtin::BI__sync_fetch_and_add_1:
5258  case Builtin::BI__sync_fetch_and_add_2:
5259  case Builtin::BI__sync_fetch_and_add_4:
5260  case Builtin::BI__sync_fetch_and_add_8:
5261  case Builtin::BI__sync_fetch_and_add_16:
5262  BuiltinIndex = 0;
5263  break;
5264 
5265  case Builtin::BI__sync_fetch_and_sub:
5266  case Builtin::BI__sync_fetch_and_sub_1:
5267  case Builtin::BI__sync_fetch_and_sub_2:
5268  case Builtin::BI__sync_fetch_and_sub_4:
5269  case Builtin::BI__sync_fetch_and_sub_8:
5270  case Builtin::BI__sync_fetch_and_sub_16:
5271  BuiltinIndex = 1;
5272  break;
5273 
5274  case Builtin::BI__sync_fetch_and_or:
5275  case Builtin::BI__sync_fetch_and_or_1:
5276  case Builtin::BI__sync_fetch_and_or_2:
5277  case Builtin::BI__sync_fetch_and_or_4:
5278  case Builtin::BI__sync_fetch_and_or_8:
5279  case Builtin::BI__sync_fetch_and_or_16:
5280  BuiltinIndex = 2;
5281  break;
5282 
5283  case Builtin::BI__sync_fetch_and_and:
5284  case Builtin::BI__sync_fetch_and_and_1:
5285  case Builtin::BI__sync_fetch_and_and_2:
5286  case Builtin::BI__sync_fetch_and_and_4:
5287  case Builtin::BI__sync_fetch_and_and_8:
5288  case Builtin::BI__sync_fetch_and_and_16:
5289  BuiltinIndex = 3;
5290  break;
5291 
5292  case Builtin::BI__sync_fetch_and_xor:
5293  case Builtin::BI__sync_fetch_and_xor_1:
5294  case Builtin::BI__sync_fetch_and_xor_2:
5295  case Builtin::BI__sync_fetch_and_xor_4:
5296  case Builtin::BI__sync_fetch_and_xor_8:
5297  case Builtin::BI__sync_fetch_and_xor_16:
5298  BuiltinIndex = 4;
5299  break;
5300 
5301  case Builtin::BI__sync_fetch_and_nand:
5302  case Builtin::BI__sync_fetch_and_nand_1:
5303  case Builtin::BI__sync_fetch_and_nand_2:
5304  case Builtin::BI__sync_fetch_and_nand_4:
5305  case Builtin::BI__sync_fetch_and_nand_8:
5306  case Builtin::BI__sync_fetch_and_nand_16:
5307  BuiltinIndex = 5;
5308  WarnAboutSemanticsChange = true;
5309  break;
5310 
5311  case Builtin::BI__sync_add_and_fetch:
5312  case Builtin::BI__sync_add_and_fetch_1:
5313  case Builtin::BI__sync_add_and_fetch_2:
5314  case Builtin::BI__sync_add_and_fetch_4:
5315  case Builtin::BI__sync_add_and_fetch_8:
5316  case Builtin::BI__sync_add_and_fetch_16:
5317  BuiltinIndex = 6;
5318  break;
5319 
5320  case Builtin::BI__sync_sub_and_fetch:
5321  case Builtin::BI__sync_sub_and_fetch_1:
5322  case Builtin::BI__sync_sub_and_fetch_2:
5323  case Builtin::BI__sync_sub_and_fetch_4:
5324  case Builtin::BI__sync_sub_and_fetch_8:
5325  case Builtin::BI__sync_sub_and_fetch_16:
5326  BuiltinIndex = 7;
5327  break;
5328 
5329  case Builtin::BI__sync_and_and_fetch:
5330  case Builtin::BI__sync_and_and_fetch_1:
5331  case Builtin::BI__sync_and_and_fetch_2:
5332  case Builtin::BI__sync_and_and_fetch_4:
5333  case Builtin::BI__sync_and_and_fetch_8:
5334  case Builtin::BI__sync_and_and_fetch_16:
5335  BuiltinIndex = 8;
5336  break;
5337 
5338  case Builtin::BI__sync_or_and_fetch:
5339  case Builtin::BI__sync_or_and_fetch_1:
5340  case Builtin::BI__sync_or_and_fetch_2:
5341  case Builtin::BI__sync_or_and_fetch_4:
5342  case Builtin::BI__sync_or_and_fetch_8:
5343  case Builtin::BI__sync_or_and_fetch_16:
5344  BuiltinIndex = 9;
5345  break;
5346 
5347  case Builtin::BI__sync_xor_and_fetch:
5348  case Builtin::BI__sync_xor_and_fetch_1:
5349  case Builtin::BI__sync_xor_and_fetch_2:
5350  case Builtin::BI__sync_xor_and_fetch_4:
5351  case Builtin::BI__sync_xor_and_fetch_8:
5352  case Builtin::BI__sync_xor_and_fetch_16:
5353  BuiltinIndex = 10;
5354  break;
5355 
5356  case Builtin::BI__sync_nand_and_fetch:
5357  case Builtin::BI__sync_nand_and_fetch_1:
5358  case Builtin::BI__sync_nand_and_fetch_2:
5359  case Builtin::BI__sync_nand_and_fetch_4:
5360  case Builtin::BI__sync_nand_and_fetch_8:
5361  case Builtin::BI__sync_nand_and_fetch_16:
5362  BuiltinIndex = 11;
5363  WarnAboutSemanticsChange = true;
5364  break;
5365 
5366  case Builtin::BI__sync_val_compare_and_swap:
5367  case Builtin::BI__sync_val_compare_and_swap_1:
5368  case Builtin::BI__sync_val_compare_and_swap_2:
5369  case Builtin::BI__sync_val_compare_and_swap_4:
5370  case Builtin::BI__sync_val_compare_and_swap_8:
5371  case Builtin::BI__sync_val_compare_and_swap_16:
5372  BuiltinIndex = 12;
5373  NumFixed = 2;
5374  break;
5375 
5376  case Builtin::BI__sync_bool_compare_and_swap:
5377  case Builtin::BI__sync_bool_compare_and_swap_1:
5378  case Builtin::BI__sync_bool_compare_and_swap_2:
5379  case Builtin::BI__sync_bool_compare_and_swap_4:
5380  case Builtin::BI__sync_bool_compare_and_swap_8:
5381  case Builtin::BI__sync_bool_compare_and_swap_16:
5382  BuiltinIndex = 13;
5383  NumFixed = 2;
5384  ResultType = Context.BoolTy;
5385  break;
5386 
5387  case Builtin::BI__sync_lock_test_and_set:
5388  case Builtin::BI__sync_lock_test_and_set_1:
5389  case Builtin::BI__sync_lock_test_and_set_2:
5390  case Builtin::BI__sync_lock_test_and_set_4:
5391  case Builtin::BI__sync_lock_test_and_set_8:
5392  case Builtin::BI__sync_lock_test_and_set_16:
5393  BuiltinIndex = 14;
5394  break;
5395 
5396  case Builtin::BI__sync_lock_release:
5397  case Builtin::BI__sync_lock_release_1:
5398  case Builtin::BI__sync_lock_release_2:
5399  case Builtin::BI__sync_lock_release_4:
5400  case Builtin::BI__sync_lock_release_8:
5401  case Builtin::BI__sync_lock_release_16:
5402  BuiltinIndex = 15;
5403  NumFixed = 0;
5404  ResultType = Context.VoidTy;
5405  break;
5406 
5407  case Builtin::BI__sync_swap:
5408  case Builtin::BI__sync_swap_1:
5409  case Builtin::BI__sync_swap_2:
5410  case Builtin::BI__sync_swap_4:
5411  case Builtin::BI__sync_swap_8:
5412  case Builtin::BI__sync_swap_16:
5413  BuiltinIndex = 16;
5414  break;
5415  }
5416 
5417  // Now that we know how many fixed arguments we expect, first check that we
5418  // have at least that many.
5419  if (TheCall->getNumArgs() < 1+NumFixed) {
5420  Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5421  << 0 << 1 + NumFixed << TheCall->getNumArgs()
5422  << Callee->getSourceRange();
5423  return ExprError();
5424  }
5425 
5426  Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5427  << Callee->getSourceRange();
5428 
5429  if (WarnAboutSemanticsChange) {
5430  Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5431  << Callee->getSourceRange();
5432  }
5433 
5434  // Get the decl for the concrete builtin from this, we can tell what the
5435  // concrete integer type we should convert to is.
5436  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5437  const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5438  FunctionDecl *NewBuiltinDecl;
5439  if (NewBuiltinID == BuiltinID)
5440  NewBuiltinDecl = FDecl;
5441  else {
5442  // Perform builtin lookup to avoid redeclaring it.
5443  DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5444  LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5445  LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5446  assert(Res.getFoundDecl());
5447  NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5448  if (!NewBuiltinDecl)
5449  return ExprError();
5450  }
5451 
5452  // The first argument --- the pointer --- has a fixed type; we
5453  // deduce the types of the rest of the arguments accordingly. Walk
5454  // the remaining arguments, converting them to the deduced value type.
5455  for (unsigned i = 0; i != NumFixed; ++i) {
5456  ExprResult Arg = TheCall->getArg(i+1);
5457 
5458  // GCC does an implicit conversion to the pointer or integer ValType. This
5459  // can fail in some cases (1i -> int**), check for this error case now.
5460  // Initialize the argument.
5462  ValType, /*consume*/ false);
5463  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5464  if (Arg.isInvalid())
5465  return ExprError();
5466 
5467  // Okay, we have something that *can* be converted to the right type. Check
5468  // to see if there is a potentially weird extension going on here. This can
5469  // happen when you do an atomic operation on something like an char* and
5470  // pass in 42. The 42 gets converted to char. This is even more strange
5471  // for things like 45.123 -> char, etc.
5472  // FIXME: Do this check.
5473  TheCall->setArg(i+1, Arg.get());
5474  }
5475 
5476  // Create a new DeclRefExpr to refer to the new decl.
5477  DeclRefExpr *NewDRE = DeclRefExpr::Create(
5478  Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5479  /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5480  DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5481 
5482  // Set the callee in the CallExpr.
5483  // FIXME: This loses syntactic information.
5484  QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5485  ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5486  CK_BuiltinFnToFnPtr);
5487  TheCall->setCallee(PromotedCall.get());
5488 
5489  // Change the result type of the call to match the original value type. This
5490  // is arbitrary, but the codegen for these builtins ins design to handle it
5491  // gracefully.
5492  TheCall->setType(ResultType);
5493 
5494  return TheCallResult;
5495 }
5496 
5497 /// SemaBuiltinNontemporalOverloaded - We have a call to
5498 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5499 /// overloaded function based on the pointer type of its last argument.
5500 ///
5501 /// This function goes through and does final semantic checking for these
5502 /// builtins.
5503 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5504  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5505  DeclRefExpr *DRE =
5506  cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5507  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5508  unsigned BuiltinID = FDecl->getBuiltinID();
5509  assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5510  BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5511  "Unexpected nontemporal load/store builtin!");
5512  bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5513  unsigned numArgs = isStore ? 2 : 1;
5514 
5515  // Ensure that we have the proper number of arguments.
5516  if (checkArgCount(*this, TheCall, numArgs))
5517  return ExprError();
5518 
5519  // Inspect the last argument of the nontemporal builtin. This should always
5520  // be a pointer type, from which we imply the type of the memory access.
5521  // Because it is a pointer type, we don't have to worry about any implicit
5522  // casts here.
5523  Expr *PointerArg = TheCall->getArg(numArgs - 1);
5524  ExprResult PointerArgResult =
5525  DefaultFunctionArrayLvalueConversion(PointerArg);
5526 
5527  if (PointerArgResult.isInvalid())
5528  return ExprError();
5529  PointerArg = PointerArgResult.get();
5530  TheCall->setArg(numArgs - 1, PointerArg);
5531 
5532  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5533  if (!pointerType) {
5534  Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5535  << PointerArg->getType() << PointerArg->getSourceRange();
5536  return ExprError();
5537  }
5538 
5539  QualType ValType = pointerType->getPointeeType();
5540 
5541  // Strip any qualifiers off ValType.
5542  ValType = ValType.getUnqualifiedType();
5543  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5544  !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5545  !ValType->isVectorType()) {
5546  Diag(DRE->getBeginLoc(),
5547  diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5548  << PointerArg->getType() << PointerArg->getSourceRange();
5549  return ExprError();
5550  }
5551 
5552  if (!isStore) {
5553  TheCall->setType(ValType);
5554  return TheCallResult;
5555  }
5556 
5557  ExprResult ValArg = TheCall->getArg(0);
5559  Context, ValType, /*consume*/ false);
5560  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5561  if (ValArg.isInvalid())
5562  return ExprError();
5563 
5564  TheCall->setArg(0, ValArg.get());
5565  TheCall->setType(Context.VoidTy);
5566  return TheCallResult;
5567 }
5568 
5569 /// CheckObjCString - Checks that the argument to the builtin
5570 /// CFString constructor is correct
5571 /// Note: It might also make sense to do the UTF-16 conversion here (would
5572 /// simplify the backend).
5573 bool Sema::CheckObjCString(Expr *Arg) {
5574  Arg = Arg->IgnoreParenCasts();
5575  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5576 
5577  if (!Literal || !Literal->isAscii()) {
5578  Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5579  << Arg->getSourceRange();
5580  return true;
5581  }
5582 
5583  if (Literal->containsNonAsciiOrNull()) {
5584  StringRef String = Literal->getString();
5585  unsigned NumBytes = String.size();
5586  SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5587  const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5588  llvm::UTF16 *ToPtr = &ToBuf[0];
5589 
5590  llvm::ConversionResult Result =
5591  llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5592  ToPtr + NumBytes, llvm::strictConversion);
5593  // Check for conversion failure.
5594  if (Result != llvm::conversionOK)
5595  Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5596  << Arg->getSourceRange();
5597  }
5598  return false;
5599 }
5600 
5601 /// CheckObjCString - Checks that the format string argument to the os_log()
5602 /// and os_trace() functions is correct, and converts it to const char *.
5603 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5604  Arg = Arg->IgnoreParenCasts();
5605  auto *Literal = dyn_cast<StringLiteral>(Arg);
5606  if (!Literal) {
5607  if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5608  Literal = ObjcLiteral->getString();
5609  }
5610  }
5611 
5612  if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5613  return ExprError(
5614  Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5615  << Arg->getSourceRange());
5616  }
5617 
5618  ExprResult Result(Literal);
5619  QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5620  InitializedEntity Entity =
5621  InitializedEntity::InitializeParameter(Context, ResultTy, false);
5622  Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5623  return Result;
5624 }
5625 
5626 /// Check that the user is calling the appropriate va_start builtin for the
5627 /// target and calling convention.
5628 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5629  const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5630  bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5631  bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5632  TT.getArch() == llvm::Triple::aarch64_32);
5633  bool IsWindows = TT.isOSWindows();
5634  bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5635  if (IsX64 || IsAArch64) {
5636  CallingConv CC = CC_C;
5637  if (const FunctionDecl *FD = S.getCurFunctionDecl())
5638  CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5639  if (IsMSVAStart) {
5640  // Don't allow this in System V ABI functions.
5641  if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5642  return S.Diag(Fn->getBeginLoc(),
5643  diag::err_ms_va_start_used_in_sysv_function);
5644  } else {
5645  // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5646  // On x64 Windows, don't allow this in System V ABI functions.
5647  // (Yes, that means there's no corresponding way to support variadic
5648  // System V ABI functions on Windows.)
5649  if ((IsWindows && CC == CC_X86_64SysV) ||
5650  (!IsWindows && CC == CC_Win64))
5651  return S.Diag(Fn->getBeginLoc(),
5652  diag::err_va_start_used_in_wrong_abi_function)
5653  << !IsWindows;
5654  }
5655  return false;
5656  }
5657 
5658  if (IsMSVAStart)
5659  return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5660  return false;
5661 }
5662 
5664  ParmVarDecl **LastParam = nullptr) {
5665  // Determine whether the current function, block, or obj-c method is variadic
5666  // and get its parameter list.
5667  bool IsVariadic = false;
5668  ArrayRef<ParmVarDecl *> Params;
5669  DeclContext *Caller = S.CurContext;
5670  if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5671  IsVariadic = Block->isVariadic();
5672  Params = Block->parameters();
5673  } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5674  IsVariadic = FD->isVariadic();
5675  Params = FD->parameters();
5676  } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5677  IsVariadic = MD->isVariadic();
5678  // FIXME: This isn't correct for methods (results in bogus warning).
5679  Params = MD->parameters();
5680  } else if (isa<CapturedDecl>(Caller)) {
5681  // We don't support va_start in a CapturedDecl.
5682  S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5683  return true;
5684  } else {
5685  // This must be some other declcontext that parses exprs.
5686  S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5687  return true;
5688  }
5689 
5690  if (!IsVariadic) {
5691  S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5692  return true;
5693  }
5694 
5695  if (LastParam)
5696  *LastParam = Params.empty() ? nullptr : Params.back();
5697 
5698  return false;
5699 }
5700 
5701 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5702 /// for validity. Emit an error and return true on failure; return false
5703 /// on success.
5704 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5705  Expr *Fn = TheCall->getCallee();
5706 
5707  if (checkVAStartABI(*this, BuiltinID, Fn))
5708  return true;
5709 
5710  if (TheCall->getNumArgs() > 2) {
5711  Diag(TheCall->getArg(2)->getBeginLoc(),
5712  diag::err_typecheck_call_too_many_args)
5713  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5714  << Fn->getSourceRange()
5715  << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5716  (*(TheCall->arg_end() - 1))->getEndLoc());
5717  return true;
5718  }
5719 
5720  if (TheCall->getNumArgs() < 2) {
5721  return Diag(TheCall->getEndLoc(),
5722  diag::err_typecheck_call_too_few_args_at_least)
5723  << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5724  }
5725 
5726  // Type-check the first argument normally.
5727  if (checkBuiltinArgument(*this, TheCall, 0))
5728  return true;
5729 
5730  // Check that the current function is variadic, and get its last parameter.
5731  ParmVarDecl *LastParam;
5732  if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5733  return true;
5734 
5735  // Verify that the second argument to the builtin is the last argument of the
5736  // current function or method.
5737  bool SecondArgIsLastNamedArgument = false;
5738  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5739 
5740  // These are valid if SecondArgIsLastNamedArgument is false after the next
5741  // block.
5742  QualType Type;
5743  SourceLocation ParamLoc;
5744  bool IsCRegister = false;
5745 
5746  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5747  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5748  SecondArgIsLastNamedArgument = PV == LastParam;
5749 
5750  Type = PV->getType();
5751  ParamLoc = PV->getLocation();
5752  IsCRegister =
5753  PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5754  }
5755  }
5756 
5757  if (!SecondArgIsLastNamedArgument)
5758  Diag(TheCall->getArg(1)->getBeginLoc(),
5759  diag::warn_second_arg_of_va_start_not_last_named_param);
5760  else if (IsCRegister || Type->isReferenceType() ||
5761  Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5762  // Promotable integers are UB, but enumerations need a bit of
5763  // extra checking to see what their promotable type actually is.
5764  if (!Type->isPromotableIntegerType())
5765  return false;
5766  if (!Type->isEnumeralType())
5767  return true;
5768  const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5769  return !(ED &&
5770  Context.typesAreCompatible(ED->getPromotionType(), Type));
5771  }()) {
5772  unsigned Reason = 0;
5773  if (Type->isReferenceType()) Reason = 1;
5774  else if (IsCRegister) Reason = 2;
5775  Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5776  Diag(ParamLoc, diag::note_parameter_type) << Type;
5777  }
5778 
5779  TheCall->setType(Context.VoidTy);
5780  return false;
5781 }
5782 
5783 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5784  // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5785  // const char *named_addr);
5786 
5787  Expr *Func = Call->getCallee();
5788 
5789  if (Call->getNumArgs() < 3)
5790  return Diag(Call->getEndLoc(),
5791  diag::err_typecheck_call_too_few_args_at_least)
5792  << 0 /*function call*/ << 3 << Call->getNumArgs();
5793 
5794  // Type-check the first argument normally.
5795  if (checkBuiltinArgument(*this, Call, 0))
5796  return true;
5797 
5798  // Check that the current function is variadic.
5799  if (checkVAStartIsInVariadicFunction(*this, Func))
5800  return true;
5801 
5802  // __va_start on Windows does not validate the parameter qualifiers
5803 
5804  const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5805  const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5806 
5807  const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5808  const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5809 
5810  const QualType &ConstCharPtrTy =
5811  Context.getPointerType(Context.CharTy.withConst());
5812  if (!Arg1Ty->isPointerType() ||
5813  Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5814  Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5815  << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5816  << 0 /* qualifier difference */
5817  << 3 /* parameter mismatch */
5818  << 2 << Arg1->getType() << ConstCharPtrTy;
5819 
5820  const QualType SizeTy = Context.getSizeType();
5821  if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5822  Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5823  << Arg2->getType() << SizeTy << 1 /* different class */
5824  << 0 /* qualifier difference */
5825  << 3 /* parameter mismatch */
5826  << 3 << Arg2->getType() << SizeTy;
5827 
5828  return false;
5829 }
5830 
5831 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5832 /// friends. This is declared to take (...), so we have to check everything.
5833 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5834  if (TheCall->getNumArgs() < 2)
5835  return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5836  << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5837  if (TheCall->getNumArgs() > 2)
5838  return Diag(TheCall->getArg(2)->getBeginLoc(),
5839  diag::err_typecheck_call_too_many_args)
5840  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5841  << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5842  (*(TheCall->arg_end() - 1))->getEndLoc());
5843 
5844  ExprResult OrigArg0 = TheCall->getArg(0);
5845  ExprResult OrigArg1 = TheCall->getArg(1);
5846 
5847  // Do standard promotions between the two arguments, returning their common
5848  // type.
5849  QualType Res = UsualArithmeticConversions(
5850  OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5851  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5852  return true;
5853 
5854  // Make sure any conversions are pushed back into the call; this is
5855  // type safe since unordered compare builtins are declared as "_Bool
5856  // foo(...)".
5857  TheCall->setArg(0, OrigArg0.get());
5858  TheCall->setArg(1, OrigArg1.get());
5859 
5860  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5861  return false;
5862 
5863  // If the common type isn't a real floating type, then the arguments were
5864  // invalid for this operation.
5865  if (Res.isNull() || !Res->isRealFloatingType())
5866  return Diag(OrigArg0.get()->getBeginLoc(),
5867  diag::err_typecheck_call_invalid_ordered_compare)
5868  << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5869  << SourceRange(OrigArg0.get()->getBeginLoc(),
5870  OrigArg1.get()->getEndLoc());
5871 
5872  return false;
5873 }
5874 
5875 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5876 /// __builtin_isnan and friends. This is declared to take (...), so we have
5877 /// to check everything. We expect the last argument to be a floating point
5878 /// value.
5879 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5880  if (TheCall->getNumArgs() < NumArgs)
5881  return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5882  << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5883  if (TheCall->getNumArgs() > NumArgs)
5884  return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5885  diag::err_typecheck_call_too_many_args)
5886  << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5887  << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5888  (*(TheCall->arg_end() - 1))->getEndLoc());
5889 
5890  // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5891  // on all preceding parameters just being int. Try all of those.
5892  for (unsigned i = 0; i < NumArgs - 1; ++i) {
5893  Expr *Arg = TheCall->getArg(i);
5894 
5895  if (Arg->isTypeDependent())
5896  return false;
5897 
5898  ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5899 
5900  if (Res.isInvalid())
5901  return true;
5902  TheCall->setArg(i, Res.get());
5903  }
5904 
5905  Expr *OrigArg = TheCall->getArg(NumArgs-1);
5906 
5907  if (OrigArg->isTypeDependent())
5908  return false;
5909 
5910  // Usual Unary Conversions will convert half to float, which we want for
5911  // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5912  // type how it is, but do normal L->Rvalue conversions.
5914  OrigArg = UsualUnaryConversions(OrigArg).get();
5915  else
5916  OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5917  TheCall->setArg(NumArgs - 1, OrigArg);
5918 
5919  // This operation requires a non-_Complex floating-point number.
5920  if (!OrigArg->getType()->isRealFloatingType())
5921  return Diag(OrigArg->getBeginLoc(),
5922  diag::err_typecheck_call_invalid_unary_fp)
5923  << OrigArg->getType() << OrigArg->getSourceRange();
5924 
5925  return false;
5926 }
5927 
5928 // Customized Sema Checking for VSX builtins that have the following signature:
5929 // vector [...] builtinName(vector [...], vector [...], const int);
5930 // Which takes the same type of vectors (any legal vector type) for the first
5931 // two arguments and takes compile time constant for the third argument.
5932 // Example builtins are :
5933 // vector double vec_xxpermdi(vector double, vector double, int);
5934 // vector short vec_xxsldwi(vector short, vector short, int);
5935 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5936  unsigned ExpectedNumArgs = 3;
5937  if (TheCall->getNumArgs() < ExpectedNumArgs)
5938  return Diag(TheCall->getEndLoc(),
5939  diag::err_typecheck_call_too_few_args_at_least)
5940  << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5941  << TheCall->getSourceRange();
5942 
5943  if (TheCall->getNumArgs() > ExpectedNumArgs)
5944  return Diag(TheCall->getEndLoc(),
5945  diag::err_typecheck_call_too_many_args_at_most)
5946  << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5947  << TheCall->getSourceRange();
5948 
5949  // Check the third argument is a compile time constant
5951  if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5952  return Diag(TheCall->getBeginLoc(),
5953  diag::err_vsx_builtin_nonconstant_argument)
5954  << 3 /* argument index */ << TheCall->getDirectCallee()
5955  << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5956  TheCall->getArg(2)->getEndLoc());
5957 
5958  QualType Arg1Ty = TheCall->getArg(0)->getType();
5959  QualType Arg2Ty = TheCall->getArg(1)->getType();
5960 
5961  // Check the type of argument 1 and argument 2 are vectors.
5962  SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5963  if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5964  (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5965  return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5966  << TheCall->getDirectCallee()
5967  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5968  TheCall->getArg(1)->getEndLoc());
5969  }
5970 
5971  // Check the first two arguments are the same type.
5972  if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5973  return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5974  << TheCall->getDirectCallee()
5975  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5976  TheCall->getArg(1)->getEndLoc());
5977  }
5978 
5979  // When default clang type checking is turned off and the customized type
5980  // checking is used, the returning type of the function must be explicitly
5981  // set. Otherwise it is _Bool by default.
5982  TheCall->setType(Arg1Ty);
5983 
5984  return false;
5985 }
5986 
5987 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5988 // This is declared to take (...), so we have to check everything.
5990  if (TheCall->getNumArgs() < 2)
5991  return ExprError(Diag(TheCall->getEndLoc(),
5992  diag::err_typecheck_call_too_few_args_at_least)
5993  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5994  << TheCall->getSourceRange());
5995 
5996  // Determine which of the following types of shufflevector we're checking:
5997  // 1) unary, vector mask: (lhs, mask)
5998  // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5999  QualType resType = TheCall->getArg(0)->getType();
6000  unsigned numElements = 0;
6001 
6002  if (!TheCall->getArg(0)->isTypeDependent() &&
6003  !TheCall->getArg(1)->isTypeDependent()) {
6004  QualType LHSType = TheCall->getArg(0)->getType();
6005  QualType RHSType = TheCall->getArg(1)->getType();
6006 
6007  if (!LHSType->isVectorType() || !RHSType->isVectorType())
6008  return ExprError(
6009  Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6010  << TheCall->getDirectCallee()
6011  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6012  TheCall->getArg(1)->getEndLoc()));
6013 
6014  numElements = LHSType->castAs<VectorType>()->getNumElements();
6015  unsigned numResElements = TheCall->getNumArgs() - 2;
6016 
6017  // Check to see if we have a call with 2 vector arguments, the unary shuffle
6018  // with mask. If so, verify that RHS is an integer vector type with the
6019  // same number of elts as lhs.
6020  if (TheCall->getNumArgs() == 2) {
6021  if (!RHSType->hasIntegerRepresentation() ||
6022  RHSType->castAs<VectorType>()->getNumElements() != numElements)
6023  return ExprError(Diag(TheCall->getBeginLoc(),
6024  diag::err_vec_builtin_incompatible_vector)
6025  << TheCall->getDirectCallee()
6026  << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6027  TheCall->getArg(1)->getEndLoc()));
6028  } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6029  return ExprError(Diag(TheCall->getBeginLoc(),
6030  diag::err_vec_builtin_incompatible_vector)
6031  << TheCall->getDirectCallee()
6032  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6033  TheCall->getArg(1)->getEndLoc()));
6034  } else if (numElements != numResElements) {
6035  QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6036  resType = Context.getVectorType(eltType, numResElements,
6038  }
6039  }
6040 
6041  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6042  if (TheCall->getArg(i)->isTypeDependent() ||
6043  TheCall->getArg(i)->isValueDependent())
6044  continue;
6045 
6046  llvm::APSInt Result(32);
6047  if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
6048  return ExprError(Diag(TheCall->getBeginLoc(),
6049  diag::err_shufflevector_nonconstant_argument)
6050  << TheCall->getArg(i)->getSourceRange());
6051 
6052  // Allow -1 which will be translated to undef in the IR.
6053  if (Result.isSigned() && Result.isAllOnesValue())
6054  continue;
6055 
6056  if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
6057  return ExprError(Diag(TheCall->getBeginLoc(),
6058  diag::err_shufflevector_argument_too_large)
6059  << TheCall->getArg(i)->getSourceRange());
6060  }
6061 
6062  SmallVector<Expr*, 32> exprs;
6063 
6064  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6065  exprs.push_back(TheCall->getArg(i));
6066  TheCall->setArg(i, nullptr);
6067  }
6068 
6069  return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6070  TheCall->getCallee()->getBeginLoc(),
6071  TheCall->getRParenLoc());
6072 }
6073 
6074 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6076  SourceLocation BuiltinLoc,
6077  SourceLocation RParenLoc) {
6078  ExprValueKind VK = VK_RValue;
6080  QualType DstTy = TInfo->getType();
6081  QualType SrcTy = E->getType();
6082 
6083  if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6084  return ExprError(Diag(BuiltinLoc,
6085  diag::err_convertvector_non_vector)
6086  << E->getSourceRange());
6087  if (!DstTy->isVectorType() && !DstTy->isDependentType())
6088  return ExprError(Diag(BuiltinLoc,
6089  diag::err_convertvector_non_vector_type));
6090 
6091  if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6092  unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6093  unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6094  if (SrcElts != DstElts)
6095  return ExprError(Diag(BuiltinLoc,
6096  diag::err_convertvector_incompatible_vector)
6097  << E->getSourceRange());
6098  }
6099 
6100  return new (Context)
6101  ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6102 }
6103 
6104 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6105 // This is declared to take (const void*, ...) and can take two
6106 // optional constant int args.
6107 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6108  unsigned NumArgs = TheCall->getNumArgs();
6109 
6110  if (NumArgs > 3)
6111  return Diag(TheCall->getEndLoc(),
6112  diag::err_typecheck_call_too_many_args_at_most)
6113  << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6114 
6115  // Argument 0 is checked for us and the remaining arguments must be
6116  // constant integers.
6117  for (unsigned i = 1; i != NumArgs; ++i)
6118  if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6119  return true;
6120 
6121  return false;
6122 }
6123 
6124 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6125 // __assume does not evaluate its arguments, and should warn if its argument
6126 // has side effects.
6127 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6128  Expr *Arg = TheCall->getArg(0);
6129  if (Arg->isInstantiationDependent()) return false;
6130 
6131  if (Arg->HasSideEffects(Context))
6132  Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6133  << Arg->getSourceRange()
6134  << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6135 
6136  return false;
6137 }
6138 
6139 /// Handle __builtin_alloca_with_align. This is declared
6140 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6141 /// than 8.
6142 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6143  // The alignment must be a constant integer.
6144  Expr *Arg = TheCall->getArg(1);
6145 
6146  // We can't check the value of a dependent argument.
6147  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6148  if (const auto *UE =
6149  dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6150  if (UE->getKind() == UETT_AlignOf ||
6151  UE->getKind() == UETT_PreferredAlignOf)
6152  Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6153  << Arg->getSourceRange();
6154 
6155  llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6156 
6157  if (!Result.isPowerOf2())
6158  return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6159  << Arg->getSourceRange();
6160 
6161  if (Result < Context.getCharWidth())
6162  return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6163  << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6164 
6165  if (Result > std::numeric_limits<int32_t>::max())
6166  return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6168  }
6169 
6170  return false;
6171 }
6172 
6173 /// Handle __builtin_assume_aligned. This is declared
6174 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6175 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6176  unsigned NumArgs = TheCall->getNumArgs();
6177 
6178  if (NumArgs > 3)
6179  return Diag(TheCall->getEndLoc(),
6180  diag::err_typecheck_call_too_many_args_at_most)
6181  << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6182 
6183  // The alignment must be a constant integer.
6184  Expr *Arg = TheCall->getArg(1);
6185 
6186  // We can't check the value of a dependent argument.
6187  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6188  llvm::APSInt Result;
6189  if (SemaBuiltinConstantArg(TheCall, 1, Result))
6190  return true;
6191 
6192  if (!Result.isPowerOf2())
6193  return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6194  << Arg->getSourceRange();
6195 
6196  // Alignment calculations can wrap around if it's greater than 2**29.
6197  unsigned MaximumAlignment = 536870912;
6198  if (Result > MaximumAlignment)
6199  Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6200  << Arg->getSourceRange() << MaximumAlignment;
6201  }
6202 
6203  if (NumArgs > 2) {
6204  ExprResult Arg(TheCall->getArg(2));
6206  Context.getSizeType(), false);
6207  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6208  if (Arg.isInvalid()) return true;
6209  TheCall->setArg(2, Arg.get());
6210  }
6211 
6212  return false;
6213 }
6214 
6215 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6216  unsigned BuiltinID =
6217  cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6218  bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6219 
6220  unsigned NumArgs = TheCall->getNumArgs();
6221  unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6222  if (NumArgs < NumRequiredArgs) {
6223  return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6224  << 0 /* function call */ << NumRequiredArgs << NumArgs
6225  << TheCall->getSourceRange();
6226  }
6227  if (NumArgs >= NumRequiredArgs + 0x100) {
6228  return Diag(TheCall->getEndLoc(),
6229  diag::err_typecheck_call_too_many_args_at_most)
6230  << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6231  << TheCall->getSourceRange();
6232  }
6233  unsigned i = 0;
6234 
6235  // For formatting call, check buffer arg.
6236  if (!IsSizeCall) {
6237  ExprResult Arg(TheCall->getArg(i));
6239  Context, Context.VoidPtrTy, false);
6240  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6241  if (Arg.isInvalid())
6242  return true;
6243  TheCall->setArg(i, Arg.get());
6244  i++;
6245  }
6246 
6247  // Check string literal arg.
6248  unsigned FormatIdx = i;
6249  {
6250  ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6251  if (Arg.isInvalid())
6252  return true;
6253  TheCall->setArg(i, Arg.get());
6254  i++;
6255  }
6256 
6257  // Make sure variadic args are scalar.
6258  unsigned FirstDataArg = i;
6259  while (i < NumArgs) {
6260  ExprResult Arg = DefaultVariadicArgumentPromotion(
6261  TheCall->getArg(i), VariadicFunction, nullptr);
6262  if (Arg.isInvalid())
6263  return true;
6264  CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6265  if (ArgSize.getQuantity() >= 0x100) {
6266  return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6267  << i << (int)ArgSize.getQuantity() << 0xff
6268  << TheCall->getSourceRange();
6269  }
6270  TheCall->setArg(i, Arg.get());
6271  i++;
6272  }
6273 
6274  // Check formatting specifiers. NOTE: We're only doing this for the non-size
6275  // call to avoid duplicate diagnostics.
6276  if (!IsSizeCall) {
6277  llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6278  ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6279  bool Success = CheckFormatArguments(
6280  Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6281  VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6282  CheckedVarArgs);
6283  if (!Success)
6284  return true;
6285  }
6286 
6287  if (IsSizeCall) {
6288  TheCall->setType(Context.getSizeType());
6289  } else {
6290  TheCall->setType(Context.VoidPtrTy);
6291  }
6292  return false;
6293 }
6294 
6295 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6296 /// TheCall is a constant expression.
6297 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6298  llvm::APSInt &Result) {
6299  Expr *Arg = TheCall->getArg(ArgNum);
6300  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6301  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6302 
6303  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6304 
6305  if (!Arg->isIntegerConstantExpr(Result, Context))
6306  return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6307  << FDecl->getDeclName() << Arg->getSourceRange();
6308 
6309  return false;
6310 }
6311 
6312 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6313 /// TheCall is a constant expression in the range [Low, High].
6314 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6315  int Low, int High, bool RangeIsError) {
6316  if (isConstantEvaluated())
6317  return false;
6318  llvm::APSInt Result;
6319 
6320  // We can't check the value of a dependent argument.
6321  Expr *Arg = TheCall->getArg(ArgNum);
6322  if (Arg->isTypeDependent() || Arg->isValueDependent())
6323  return false;
6324 
6325  // Check constant-ness first.
6326  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6327  return true;
6328 
6329  if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6330  if (RangeIsError)
6331  return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6332  << Result.toString(10) << Low << High << Arg->getSourceRange();
6333  else
6334  // Defer the warning until we know if the code will be emitted so that
6335  // dead code can ignore this.
6336  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6337  PDiag(diag::warn_argument_invalid_range)
6338  << Result.toString(10) << Low << High
6339  << Arg->getSourceRange());
6340  }
6341 
6342  return false;
6343 }
6344 
6345 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6346 /// TheCall is a constant expression is a multiple of Num..
6347 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6348  unsigned Num) {
6349  llvm::APSInt Result;
6350 
6351  // We can't check the value of a dependent argument.
6352  Expr *Arg = TheCall->getArg(ArgNum);
6353  if (Arg->isTypeDependent() || Arg->isValueDependent())
6354  return false;
6355 
6356  // Check constant-ness first.
6357  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6358  return true;
6359 
6360  if (Result.getSExtValue() % Num != 0)
6361  return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6362  << Num << Arg->getSourceRange();
6363 
6364  return false;
6365 }
6366 
6367 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6368 /// constant expression representing a power of 2.
6369 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6370  llvm::APSInt Result;
6371 
6372  // We can't check the value of a dependent argument.
6373  Expr *Arg = TheCall->getArg(ArgNum);
6374  if (Arg->isTypeDependent() || Arg->isValueDependent())
6375  return false;
6376 
6377  // Check constant-ness first.
6378  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6379  return true;
6380 
6381  // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6382  // and only if x is a power of 2.
6383  if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6384  return false;
6385 
6386  return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6387  << Arg->getSourceRange();
6388 }
6389 
6391  if (Value.isNegative())
6392  return false;
6393 
6394  // Check if it's a shifted byte, by shifting it down
6395  while (true) {
6396  // If the value fits in the bottom byte, the check passes.
6397  if (Value < 0x100)
6398  return true;
6399 
6400  // Otherwise, if the value has _any_ bits in the bottom byte, the check
6401  // fails.
6402  if ((Value & 0xFF) != 0)
6403  return false;
6404 
6405  // If the bottom 8 bits are all 0, but something above that is nonzero,
6406  // then shifting the value right by 8 bits won't affect whether it's a
6407  // shifted byte or not. So do that, and go round again.
6408  Value >>= 8;
6409  }
6410 }
6411 
6412 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6413 /// a constant expression representing an arbitrary byte value shifted left by
6414 /// a multiple of 8 bits.
6415 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum) {
6416  llvm::APSInt Result;
6417 
6418  // We can't check the value of a dependent argument.
6419  Expr *Arg = TheCall->getArg(ArgNum);
6420  if (Arg->isTypeDependent() || Arg->isValueDependent())
6421  return false;
6422 
6423  // Check constant-ness first.
6424  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6425  return true;
6426 
6427  if (IsShiftedByte(Result))
6428  return false;
6429 
6430  return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6431  << Arg->getSourceRange();
6432 }
6433 
6434 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6435 /// TheCall is a constant expression representing either a shifted byte value,
6436 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6437 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6438 /// Arm MVE intrinsics.
6439 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6440  int ArgNum) {
6441  llvm::APSInt Result;
6442 
6443  // We can't check the value of a dependent argument.
6444  Expr *Arg = TheCall->getArg(ArgNum);
6445  if (Arg->isTypeDependent() || Arg->isValueDependent())
6446  return false;
6447 
6448  // Check constant-ness first.
6449  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6450  return true;
6451 
6452  // Check to see if it's in either of the required forms.
6453  if (IsShiftedByte(Result) ||
6454  (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6455  return false;
6456 
6457  return Diag(TheCall->getBeginLoc(),
6458  diag::err_argument_not_shifted_byte_or_xxff)
6459  << Arg->getSourceRange();
6460 }
6461 
6462 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6463 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6464  if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6465  if (checkArgCount(*this, TheCall, 2))
6466  return true;
6467  Expr *Arg0 = TheCall->getArg(0);
6468  Expr *Arg1 = TheCall->getArg(1);
6469 
6470  ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6471  if (FirstArg.isInvalid())
6472  return true;
6473  QualType FirstArgType = FirstArg.get()->getType();
6474  if (!FirstArgType->isAnyPointerType())
6475  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6476  << "first" << FirstArgType << Arg0->getSourceRange();
6477  TheCall->setArg(0, FirstArg.get());
6478 
6479  ExprResult SecArg = DefaultLvalueConversion(Arg1);
6480  if (SecArg.isInvalid())
6481  return true;
6482  QualType SecArgType = SecArg.get()->getType();
6483  if (!SecArgType->isIntegerType())
6484  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6485  << "second" << SecArgType << Arg1->getSourceRange();
6486 
6487  // Derive the return type from the pointer argument.
6488  TheCall->setType(FirstArgType);
6489  return false;
6490  }
6491 
6492  if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6493  if (checkArgCount(*this, TheCall, 2))
6494  return true;
6495 
6496  Expr *Arg0 = TheCall->getArg(0);
6497  ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6498  if (FirstArg.isInvalid())
6499  return true;
6500  QualType FirstArgType = FirstArg.get()->getType();
6501  if (!FirstArgType->isAnyPointerType())
6502  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6503  << "first" << FirstArgType << Arg0->getSourceRange();
6504  TheCall->setArg(0, FirstArg.get());
6505 
6506  // Derive the return type from the pointer argument.
6507  TheCall->setType(FirstArgType);
6508 
6509  // Second arg must be an constant in range [0,15]
6510  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6511  }
6512 
6513  if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6514  if (checkArgCount(*this, TheCall, 2))
6515  return true;
6516  Expr *Arg0 = TheCall->getArg(0);
6517  Expr *Arg1 = TheCall->getArg(1);
6518 
6519  ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6520  if (FirstArg.isInvalid())
6521  return true;
6522  QualType FirstArgType = FirstArg.get()->getType();
6523  if (!FirstArgType->isAnyPointerType())
6524  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6525  << "first" << FirstArgType << Arg0->getSourceRange();
6526 
6527  QualType SecArgType = Arg1->getType();
6528  if (!SecArgType->isIntegerType())
6529  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6530  << "second" << SecArgType << Arg1->getSourceRange();
6531  TheCall->setType(Context.IntTy);
6532  return false;
6533  }
6534 
6535  if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6536  BuiltinID == AArch64::BI__builtin_arm_stg) {
6537  if (checkArgCount(*this, TheCall, 1))
6538  return true;
6539  Expr *Arg0 = TheCall->getArg(0);
6540  ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6541  if (FirstArg.isInvalid())
6542  return true;
6543 
6544  QualType FirstArgType = FirstArg.get()->getType();
6545  if (!FirstArgType->isAnyPointerType())
6546  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6547  << "first" << FirstArgType << Arg0->getSourceRange();
6548  TheCall->setArg(0, FirstArg.get());
6549 
6550  // Derive the return type from the pointer argument.
6551  if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6552  TheCall->setType(FirstArgType);
6553  return false;
6554  }
6555 
6556  if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6557  Expr *ArgA = TheCall->getArg(0);
6558  Expr *ArgB = TheCall->getArg(1);
6559 
6560  ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6561  ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6562 
6563  if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6564  return true;
6565 
6566  QualType ArgTypeA = ArgExprA.get()->getType();
6567  QualType ArgTypeB = ArgExprB.get()->getType();
6568 
6569  auto isNull = [&] (Expr *E) -> bool {
6570  return E->isNullPointerConstant(
6571  Context, Expr::NPC_ValueDependentIsNotNull); };
6572 
6573  // argument should be either a pointer or null
6574  if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6575  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6576  << "first" << ArgTypeA << ArgA->getSourceRange();
6577 
6578  if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6579  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6580  << "second" << ArgTypeB << ArgB->getSourceRange();
6581 
6582  // Ensure Pointee types are compatible
6583  if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6584  ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6585  QualType pointeeA = ArgTypeA->getPointeeType();
6586  QualType pointeeB = ArgTypeB->getPointeeType();
6587  if (!Context.typesAreCompatible(
6588  Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6589  Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6590  return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6591  << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
6592  << ArgB->getSourceRange();
6593  }
6594  }
6595 
6596  // at least one argument should be pointer type
6597  if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6598  return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6599  << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6600 
6601  if (isNull(ArgA)) // adopt type of the other pointer
6602  ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6603 
6604  if (isNull(ArgB))
6605  ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6606 
6607  TheCall->setArg(0, ArgExprA.get());
6608  TheCall->setArg(1, ArgExprB.get());
6609  TheCall->setType(Context.LongLongTy);
6610  return false;
6611  }
6612  assert(false && "Unhandled ARM MTE intrinsic");
6613  return true;
6614 }
6615 
6616 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6617 /// TheCall is an ARM/AArch64 special register string literal.
6618 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6619  int ArgNum, unsigned ExpectedFieldNum,
6620  bool AllowName) {
6621  bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6622  BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6623  BuiltinID == ARM::BI__builtin_arm_rsr ||
6624  BuiltinID == ARM::BI__builtin_arm_rsrp ||
6625  BuiltinID == ARM::BI__builtin_arm_wsr ||
6626  BuiltinID == ARM::BI__builtin_arm_wsrp;
6627  bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6628  BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6629  BuiltinID == AArch64::BI__builtin_arm_rsr ||
6630  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6631  BuiltinID == AArch64::BI__builtin_arm_wsr ||
6632  BuiltinID == AArch64::BI__builtin_arm_wsrp;
6633  assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6634 
6635  // We can't check the value of a dependent argument.
6636  Expr *Arg = TheCall->getArg(ArgNum);
6637  if (Arg->isTypeDependent() || Arg->isValueDependent())
6638  return false;
6639 
6640  // Check if the argument is a string literal.
6641  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6642  return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6643  << Arg->getSourceRange();
6644 
6645  // Check the type of special register given.
6646  StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6648  Reg.split(Fields, ":");
6649 
6650  if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6651  return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6652  << Arg->getSourceRange();
6653 
6654  // If the string is the name of a register then we cannot check that it is
6655  // valid here but if the string is of one the forms described in ACLE then we
6656  // can check that the supplied fields are integers and within the valid
6657  // ranges.
6658  if (Fields.size() > 1) {
6659  bool FiveFields = Fields.size() == 5;
6660 
6661  bool ValidString = true;
6662  if (IsARMBuiltin) {
6663  ValidString &= Fields[0].startswith_lower("cp") ||
6664  Fields[0].startswith_lower("p");
6665  if (ValidString)
6666  Fields[0] =
6667  Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6668 
6669  ValidString &= Fields[2].startswith_lower("c");
6670  if (ValidString)
6671  Fields[2] = Fields[2].drop_front(1);
6672 
6673  if (FiveFields) {
6674  ValidString &= Fields[3].startswith_lower("c");
6675  if (ValidString)
6676  Fields[3] = Fields[3].drop_front(1);
6677  }
6678  }
6679 
6680  SmallVector<int, 5> Ranges;
6681  if (FiveFields)
6682  Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6683  else
6684  Ranges.append({15, 7, 15});
6685 
6686  for (unsigned i=0; i<Fields.size(); ++i) {
6687  int IntField;
6688  ValidString &= !Fields[i].getAsInteger(10, IntField);
6689  ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6690  }
6691 
6692  if (!ValidString)
6693  return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6694  << Arg->getSourceRange();
6695  } else if (IsAArch64Builtin && Fields.size() == 1) {
6696  // If the register name is one of those that appear in the condition below
6697  // and the special register builtin being used is one of the write builtins,
6698  // then we require that the argument provided for writing to the register
6699  // is an integer constant expression. This is because it will be lowered to
6700  // an MSR (immediate) instruction, so we need to know the immediate at
6701  // compile time.
6702  if (TheCall->getNumArgs() != 2)
6703  return false;
6704 
6705  std::string RegLower = Reg.lower();
6706  if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6707  RegLower != "pan" && RegLower != "uao")
6708  return false;
6709 
6710  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6711  }
6712 
6713  return false;
6714 }
6715 
6716 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6717 /// This checks that the target supports __builtin_longjmp and
6718 /// that val is a constant 1.
6719 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6720  if (!Context.getTargetInfo().hasSjLjLowering())
6721  return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6722  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6723 
6724  Expr *Arg = TheCall->getArg(1);
6725  llvm::APSInt Result;
6726 
6727  // TODO: This is less than ideal. Overload this to take a value.
6728  if (SemaBuiltinConstantArg(TheCall, 1, Result))
6729  return true;
6730 
6731  if (Result != 1)
6732  return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6733  << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6734 
6735  return false;
6736 }
6737 
6738 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6739 /// This checks that the target supports __builtin_setjmp.
6740 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6741  if (!Context.getTargetInfo().hasSjLjLowering())
6742  return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6743  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6744  return false;
6745 }
6746 
6747 namespace {
6748 
6749 class UncoveredArgHandler {
6750  enum { Unknown = -1, AllCovered = -2 };
6751 
6752  signed FirstUncoveredArg = Unknown;
6753  SmallVector<const Expr *, 4> DiagnosticExprs;
6754 
6755 public:
6756  UncoveredArgHandler() = default;
6757 
6758  bool hasUncoveredArg() const {
6759  return (FirstUncoveredArg >= 0);
6760  }
6761 
6762  unsigned getUncoveredArg() const {
6763  assert(hasUncoveredArg() && "no uncovered argument");
6764  return FirstUncoveredArg;
6765  }
6766 
6767  void setAllCovered() {
6768  // A string has been found with all arguments covered, so clear out
6769  // the diagnostics.
6770  DiagnosticExprs.clear();
6771  FirstUncoveredArg = AllCovered;
6772  }
6773 
6774  void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6775  assert(NewFirstUncoveredArg >= 0 && "Outside range");
6776 
6777  // Don't update if a previous string covers all arguments.
6778  if (FirstUncoveredArg == AllCovered)
6779  return;
6780 
6781  // UncoveredArgHandler tracks the highest uncovered argument index
6782  // and with it all the strings that match this index.
6783  if (NewFirstUncoveredArg == FirstUncoveredArg)
6784  DiagnosticExprs.push_back(StrExpr);
6785  else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6786  DiagnosticExprs.clear();
6787  DiagnosticExprs.push_back(StrExpr);
6788  FirstUncoveredArg = NewFirstUncoveredArg;
6789  }
6790  }
6791 
6792  void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6793 };
6794 
6796  SLCT_NotALiteral,
6797  SLCT_UncheckedLiteral,
6798  SLCT_CheckedLiteral
6799 };
6800 
6801 } // namespace
6802 
6804  BinaryOperatorKind BinOpKind,
6805  bool AddendIsRight) {
6806  unsigned BitWidth = Offset.getBitWidth();
6807  unsigned AddendBitWidth = Addend.getBitWidth();
6808  // There might be negative interim results.
6809  if (Addend.isUnsigned()) {
6810  Addend = Addend.zext(++AddendBitWidth);
6811  Addend.setIsSigned(true);
6812  }
6813  // Adjust the bit width of the APSInts.
6814  if (AddendBitWidth > BitWidth) {
6815  Offset = Offset.sext(AddendBitWidth);
6816  BitWidth = AddendBitWidth;
6817  } else if (BitWidth > AddendBitWidth) {
6818  Addend = Addend.sext(BitWidth);
6819  }
6820 
6821  bool Ov = false;
6822  llvm::APSInt ResOffset = Offset;
6823  if (BinOpKind == BO_Add)
6824  ResOffset = Offset.sadd_ov(Addend, Ov);
6825  else {
6826  assert(AddendIsRight && BinOpKind == BO_Sub &&
6827  "operator must be add or sub with addend on the right");
6828  ResOffset = Offset.ssub_ov(Addend, Ov);
6829  }
6830 
6831  // We add an offset to a pointer here so we should support an offset as big as
6832  // possible.
6833  if (Ov) {
6834  assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6835  "index (intermediate) result too big");
6836  Offset = Offset.sext(2 * BitWidth);
6837  sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6838  return;
6839  }
6840 
6841  Offset = ResOffset;
6842 }
6843 
6844 namespace {
6845 
6846 // This is a wrapper class around StringLiteral to support offsetted string
6847 // literals as format strings. It takes the offset into account when returning
6848 // the string and its length or the source locations to display notes correctly.
6849 class FormatStringLiteral {
6850  const StringLiteral *FExpr;
6851  int64_t Offset;
6852 
6853  public:
6854  FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6855  : FExpr(fexpr), Offset(Offset) {}
6856 
6857  StringRef getString() const {
6858  return FExpr->getString().drop_front(Offset);
6859  }
6860 
6861  unsigned getByteLength() const {
6862  return FExpr->getByteLength() - getCharByteWidth() * Offset;
6863  }
6864 
6865  unsigned getLength() const { return FExpr->getLength() - Offset; }
6866  unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6867 
6868  StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6869 
6870  QualType getType() const { return FExpr->getType(); }
6871 
6872  bool isAscii() const { return FExpr->isAscii(); }
6873  bool isWide() const { return FExpr->isWide(); }
6874  bool isUTF8() const { return FExpr->isUTF8(); }
6875  bool isUTF16() const { return FExpr->isUTF16(); }
6876  bool isUTF32() const { return FExpr->isUTF32(); }
6877  bool isPascal() const { return FExpr->isPascal(); }
6878 
6879  SourceLocation getLocationOfByte(
6880  unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6881  const TargetInfo &Target, unsigned *StartToken = nullptr,
6882  unsigned *StartTokenByteOffset = nullptr) const {
6883  return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6884  StartToken, StartTokenByteOffset);
6885  }
6886 
6887  SourceLocation getBeginLoc() const LLVM_READONLY {
6888  return FExpr->getBeginLoc().getLocWithOffset(Offset);
6889  }
6890 
6891  SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6892 };
6893 
6894 } // namespace
6895 
6896 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6897  const Expr *OrigFormatExpr,
6898  ArrayRef<const Expr *> Args,
6899  bool HasVAListArg, unsigned format_idx,
6900  unsigned firstDataArg,
6902  bool inFunctionCall,
6903  Sema::VariadicCallType CallType,
6904  llvm::SmallBitVector &CheckedVarArgs,
6905  UncoveredArgHandler &UncoveredArg,
6906  bool IgnoreStringsWithoutSpecifiers);
6907 
6908 // Determine if an expression is a string literal or constant string.
6909 // If this function returns false on the arguments to a function expecting a
6910 // format string, we will usually need to emit a warning.
6911 // True string literals are then checked by CheckFormatString.
6913 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6914  bool HasVAListArg, unsigned format_idx,
6915  unsigned firstDataArg, Sema::FormatStringType Type,
6916  Sema::VariadicCallType CallType, bool InFunctionCall,
6917  llvm::SmallBitVector &CheckedVarArgs,
6918  UncoveredArgHandler &UncoveredArg,
6920  bool IgnoreStringsWithoutSpecifiers = false) {
6921  if (S.isConstantEvaluated())
6922  return SLCT_NotALiteral;
6923  tryAgain:
6924  assert(Offset.isSigned() && "invalid offset");
6925 
6926  if (E->isTypeDependent() || E->isValueDependent())
6927  return SLCT_NotALiteral;
6928 
6929  E = E->IgnoreParenCasts();
6930 
6932  // Technically -Wformat-nonliteral does not warn about this case.
6933  // The behavior of printf and friends in this case is implementation
6934  // dependent. Ideally if the format string cannot be null then
6935  // it should have a 'nonnull' attribute in the function prototype.
6936  return SLCT_UncheckedLiteral;
6937 
6938  switch (E->getStmtClass()) {
6939  case Stmt::BinaryConditionalOperatorClass:
6940  case Stmt::ConditionalOperatorClass: {
6941  // The expression is a literal if both sub-expressions were, and it was
6942  // completely checked only if both sub-expressions were checked.
6943  const AbstractConditionalOperator *C =
6944  cast<AbstractConditionalOperator>(E);
6945 
6946  // Determine whether it is necessary to check both sub-expressions, for
6947  // example, because the condition expression is a constant that can be
6948  // evaluated at compile time.
6949  bool CheckLeft = true, CheckRight = true;
6950 
6951  bool Cond;
6952  if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6953  S.isConstantEvaluated())) {
6954  if (Cond)
6955  CheckRight = false;
6956  else
6957  CheckLeft = false;
6958  }
6959 
6960  // We need to maintain the offsets for the right and the left hand side
6961  // separately to check if every possible indexed expression is a valid
6962  // string literal. They might have different offsets for different string
6963  // literals in the end.
6965  if (!CheckLeft)
6966  Left = SLCT_UncheckedLiteral;
6967  else {
6968  Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6969  HasVAListArg, format_idx, firstDataArg,
6970  Type, CallType, InFunctionCall,
6971  CheckedVarArgs, UncoveredArg, Offset,
6972  IgnoreStringsWithoutSpecifiers);
6973  if (Left == SLCT_NotALiteral || !CheckRight) {
6974  return Left;
6975  }
6976  }
6977 
6979  S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6980  Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6981  IgnoreStringsWithoutSpecifiers);
6982 
6983  return (CheckLeft && Left < Right) ? Left : Right;
6984  }
6985 
6986  case Stmt::ImplicitCastExprClass:
6987  E = cast<ImplicitCastExpr>(E)->getSubExpr();
6988  goto tryAgain;
6989 
6990  case Stmt::OpaqueValueExprClass:
6991  if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6992  E = src;
6993  goto tryAgain;
6994  }
6995  return SLCT_NotALiteral;
6996 
6997  case Stmt::PredefinedExprClass:
6998  // While __func__, etc., are technically not string literals, they
6999  // cannot contain format specifiers and thus are not a security
7000  // liability.
7001  return SLCT_UncheckedLiteral;
7002 
7003  case Stmt::DeclRefExprClass: {
7004  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7005 
7006  // As an exception, do not flag errors for variables binding to
7007  // const string literals.
7008  if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7009  bool isConstant = false;
7010  QualType T = DR->getType();
7011 
7012  if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7013  isConstant = AT->getElementType().isConstant(S.Context);
7014  } else if (const PointerType *PT = T->getAs<PointerType>()) {
7015  isConstant = T.isConstant(S.Context) &&
7016  PT->getPointeeType().isConstant(S.Context);
7017  } else if (T->isObjCObjectPointerType()) {
7018  // In ObjC, there is usually no "const ObjectPointer" type,
7019  // so don't check if the pointee type is constant.
7020  isConstant = T.isConstant(S.Context);
7021  }
7022 
7023  if (isConstant) {
7024  if (const Expr *Init = VD->getAnyInitializer()) {
7025  // Look through initializers like const char c[] = { "foo" }
7026  if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7027  if (InitList->isStringLiteralInit())
7028  Init = InitList->getInit(0)->IgnoreParenImpCasts();
7029  }
7030  return checkFormatStringExpr(S, Init, Args,
7031  HasVAListArg, format_idx,
7032  firstDataArg, Type, CallType,
7033  /*InFunctionCall*/ false, CheckedVarArgs,
7034  UncoveredArg, Offset);
7035  }
7036  }
7037 
7038  // For vprintf* functions (i.e., HasVAListArg==true), we add a
7039  // special check to see if the format string is a function parameter
7040  // of the function calling the printf function. If the function
7041  // has an attribute indicating it is a printf-like function, then we
7042  // should suppress warnings concerning non-literals being used in a call
7043  // to a vprintf function. For example:
7044  //
7045  // void
7046  // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7047  // va_list ap;
7048  // va_start(ap, fmt);
7049  // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
7050  // ...
7051  // }
7052  if (HasVAListArg) {
7053  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7054  if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7055  int PVIndex = PV->getFunctionScopeIndex() + 1;
7056  for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7057  // adjust for implicit parameter
7058  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7059  if (MD->isInstance())
7060  ++PVIndex;
7061  // We also check if the formats are compatible.
7062  // We can't pass a 'scanf' string to a 'printf' function.
7063  if (PVIndex == PVFormat->getFormatIdx() &&
7064  Type == S.GetFormatStringType(PVFormat))
7065  return SLCT_UncheckedLiteral;
7066  }
7067  }
7068  }
7069  }
7070  }
7071 
7072  return SLCT_NotALiteral;
7073  }
7074 
7075  case Stmt::CallExprClass:
7076  case Stmt::CXXMemberCallExprClass: {
7077  const CallExpr *CE = cast<CallExpr>(E);
7078  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7079  bool IsFirst = true;
7080  StringLiteralCheckType CommonResult;
7081  for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7082  const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7084  S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7085  CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7086  IgnoreStringsWithoutSpecifiers);
7087  if (IsFirst) {
7088  CommonResult = Result;
7089  IsFirst = false;
7090  }
7091  }
7092  if (!IsFirst)
7093  return CommonResult;
7094 
7095  if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7096  unsigned BuiltinID = FD->getBuiltinID();
7097  if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7098  BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7099  const Expr *Arg = CE->getArg(0);
7100  return checkFormatStringExpr(S, Arg, Args,
7101  HasVAListArg, format_idx,
7102  firstDataArg, Type, CallType,
7103  InFunctionCall, CheckedVarArgs,
7104  UncoveredArg, Offset,
7105  IgnoreStringsWithoutSpecifiers);
7106  }
7107  }
7108  }
7109 
7110  return SLCT_NotALiteral;
7111  }
7112  case Stmt::ObjCMessageExprClass: {
7113  const auto *ME = cast<ObjCMessageExpr>(E);
7114  if (const auto *MD = ME->getMethodDecl()) {
7115  if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7116  // As a special case heuristic, if we're using the method -[NSBundle
7117  // localizedStringForKey:value:table:], ignore any key strings that lack
7118  // format specifiers. The idea is that if the key doesn't have any
7119  // format specifiers then its probably just a key to map to the
7120  // localized strings. If it does have format specifiers though, then its
7121  // likely that the text of the key is the format string in the
7122  // programmer's language, and should be checked.
7123  const ObjCInterfaceDecl *IFace;
7124  if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7125  IFace->getIdentifier()->isStr("NSBundle") &&
7126  MD->getSelector().isKeywordSelector(
7127  {"localizedStringForKey", "value", "table"})) {
7128  IgnoreStringsWithoutSpecifiers = true;
7129  }
7130 
7131  const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7132  return checkFormatStringExpr(
7133  S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7134  CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7135  IgnoreStringsWithoutSpecifiers);
7136  }
7137  }
7138 
7139  return SLCT_NotALiteral;
7140  }
7141  case Stmt::ObjCStringLiteralClass:
7142  case Stmt::StringLiteralClass: {
7143  const StringLiteral *StrE = nullptr;
7144 
7145  if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7146  StrE = ObjCFExpr->getString();
7147  else
7148  StrE = cast<StringLiteral>(E);
7149 
7150  if (StrE) {
7151  if (Offset.isNegative() || Offset > StrE->getLength()) {
7152  // TODO: It would be better to have an explicit warning for out of
7153  // bounds literals.
7154  return SLCT_NotALiteral;
7155  }
7156  FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7157  CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7158  firstDataArg, Type, InFunctionCall, CallType,
7159  CheckedVarArgs, UncoveredArg,
7160  IgnoreStringsWithoutSpecifiers);
7161  return SLCT_CheckedLiteral;
7162  }
7163 
7164  return SLCT_NotALiteral;
7165  }
7166  case Stmt::BinaryOperatorClass: {
7167  const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7168 
7169  // A string literal + an int offset is still a string literal.
7170  if (BinOp->isAdditiveOp()) {
7171  Expr::EvalResult LResult, RResult;
7172 
7173  bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7175  bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7177 
7178  if (LIsInt != RIsInt) {
7179  BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7180 
7181  if (LIsInt) {
7182  if (BinOpKind == BO_Add) {
7183  sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7184  E = BinOp->getRHS();
7185  goto tryAgain;
7186  }
7187  } else {
7188  sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7189  E = BinOp->getLHS();
7190  goto tryAgain;
7191  }
7192  }
7193  }
7194 
7195  return SLCT_NotALiteral;
7196  }
7197  case Stmt::UnaryOperatorClass: {
7198  const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7199  auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7200  if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7201  Expr::EvalResult IndexResult;
7202  if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7204  S.isConstantEvaluated())) {
7205  sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7206  /*RHS is int*/ true);
7207  E = ASE->getBase();
7208  goto tryAgain;
7209  }
7210  }
7211 
7212  return SLCT_NotALiteral;
7213  }
7214 
7215  default:
7216  return SLCT_NotALiteral;
7217  }
7218 }
7219 
7221  return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7222  .Case("scanf", FST_Scanf)
7223  .Cases("printf", "printf0", FST_Printf)
7224  .Cases("NSString", "CFString", FST_NSString)
7225  .Case("strftime", FST_Strftime)
7226  .Case("strfmon", FST_Strfmon)
7227  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7228  .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7229  .Case("os_trace", FST_OSLog)
7230  .Case("os_log", FST_OSLog)
7231  .Default(FST_Unknown);
7232 }
7233 
7234 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7235 /// functions) for correct use of format strings.
7236 /// Returns true if a format string has been fully checked.
7237 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7239  bool IsCXXMember,
7240  VariadicCallType CallType,
7241  SourceLocation Loc, SourceRange Range,
7242  llvm::SmallBitVector &CheckedVarArgs) {
7243  FormatStringInfo FSI;
7244  if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7245  return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7246  FSI.FirstDataArg, GetFormatStringType(Format),
7247  CallType, Loc, Range, CheckedVarArgs);
7248  return false;
7249 }
7250 
7251 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7252  bool HasVAListArg, unsigned format_idx,
7253  unsigned firstDataArg, FormatStringType Type,
7254  VariadicCallType CallType,
7255  SourceLocation Loc, SourceRange Range,
7256  llvm::SmallBitVector &CheckedVarArgs) {
7257  // CHECK: printf/scanf-like function is called with no format string.
7258  if (format_idx >= Args.size()) {
7259  Diag(Loc, diag::warn_missing_format_string) << Range;
7260  return false;
7261  }
7262 
7263  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7264 
7265  // CHECK: format string is not a string literal.
7266  //
7267  // Dynamically generated format strings are difficult to
7268  // automatically vet at compile time. Requiring that format strings
7269  // are string literals: (1) permits the checking of format strings by
7270  // the compiler and thereby (2) can practically remove the source of
7271  // many format string exploits.
7272 
7273  // Format string can be either ObjC string (e.g. @"%d") or
7274  // C string (e.g. "%d")
7275  // ObjC string uses the same format specifiers as C string, so we can use
7276  // the same format string checking logic for both ObjC and C strings.
7277  UncoveredArgHandler UncoveredArg;
7279  checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7280  format_idx, firstDataArg, Type, CallType,
7281  /*IsFunctionCall*/ true, CheckedVarArgs,
7282  UncoveredArg,
7283  /*no string offset*/ llvm::APSInt(64, false) = 0);
7284 
7285  // Generate a diagnostic where an uncovered argument is detected.
7286  if (UncoveredArg.hasUncoveredArg()) {
7287  unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7288  assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7289  UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7290  }
7291 
7292  if (CT != SLCT_NotALiteral)
7293  // Literal format string found, check done!
7294  return CT == SLCT_CheckedLiteral;
7295 
7296  // Strftime is particular as it always uses a single 'time' argument,
7297  // so it is safe to pass a non-literal string.
7298  if (Type == FST_Strftime)
7299  return false;
7300 
7301  // Do not emit diag when the string param is a macro expansion and the
7302  // format is either NSString or CFString. This is a hack to prevent
7303  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7304  // which are usually used in place of NS and CF string literals.
7305  SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7306  if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7307  return false;
7308 
7309  // If there are no arguments specified, warn with -Wformat-security, otherwise
7310  // warn only with -Wformat-nonliteral.
7311  if (Args.size() == firstDataArg) {
7312  Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7313  << OrigFormatExpr->getSourceRange();
7314  switch (Type) {
7315  default:
7316  break;
7317  case FST_Kprintf:
7318  case FST_FreeBSDKPrintf:
7319  case FST_Printf:
7320  Diag(FormatLoc, diag::note_format_security_fixit)
7321  << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7322  break;
7323  case FST_NSString:
7324  Diag(FormatLoc, diag::note_format_security_fixit)
7325  << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7326  break;
7327  }
7328  } else {
7329  Diag(FormatLoc, diag::warn_format_nonliteral)
7330  << OrigFormatExpr->getSourceRange();
7331  }
7332  return false;
7333 }
7334 
7335 namespace {
7336 
7337 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7338 protected:
7339  Sema &S;
7340  const FormatStringLiteral *FExpr;
7341  const Expr *OrigFormatExpr;
7342  const Sema::FormatStringType FSType;
7343  const unsigned FirstDataArg;
7344  const unsigned NumDataArgs;
7345  const char *Beg; // Start of format string.
7346  const bool HasVAListArg;
7348  unsigned FormatIdx;
7349  llvm::SmallBitVector CoveredArgs;
7350  bool usesPositionalArgs = false;
7351  bool atFirstArg = true;
7352  bool inFunctionCall;
7353  Sema::VariadicCallType CallType;
7354  llvm::SmallBitVector &CheckedVarArgs;
7355  UncoveredArgHandler &UncoveredArg;
7356 
7357 public:
7358  CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7359  const Expr *origFormatExpr,
7360  const Sema::FormatStringType type, unsigned firstDataArg,
7361  unsigned numDataArgs, const char *beg, bool hasVAListArg,
7362  ArrayRef<const Expr *> Args, unsigned formatIdx,
7363  bool inFunctionCall, Sema::VariadicCallType callType,
7364  llvm::SmallBitVector &CheckedVarArgs,
7365  UncoveredArgHandler &UncoveredArg)
7366  : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7367  FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7368  HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7369  inFunctionCall(inFunctionCall), CallType(callType),
7370  CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7371  CoveredArgs.resize(numDataArgs);
7372  CoveredArgs.reset();
7373  }
7374 
7375  void DoneProcessing();
7376 
7377  void HandleIncompleteSpecifier(const char *startSpecifier,
7378  unsigned specifierLen) override;
7379 
7380  void HandleInvalidLengthModifier(
7383  const char *startSpecifier, unsigned specifierLen,
7384  unsigned DiagID);
7385 
7386  void HandleNonStandardLengthModifier(
7388  const char *startSpecifier, unsigned specifierLen);
7389 
7390  void HandleNonStandardConversionSpecifier(
7392  const char *startSpecifier, unsigned specifierLen);
7393 
7394  void HandlePosition(const char *startPos, unsigned posLen) override;
7395 
7396  void HandleInvalidPosition(const char *startSpecifier,
7397  unsigned specifierLen,
7399 
7400  void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7401 
7402  void HandleNullChar(const char *nullCharacter) override;
7403 
7404  template <typename Range>
7405  static void
7406  EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7407  const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7408  bool IsStringLocation, Range StringRange,
7409  ArrayRef<FixItHint> Fixit = None);
7410 
7411 protected:
7412  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7413  const char *startSpec,
7414  unsigned specifierLen,
7415  const char *csStart, unsigned csLen);
7416 
7417  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7418  const char *startSpec,
7419  unsigned specifierLen);
7420 
7421  SourceRange getFormatStringRange();
7422  CharSourceRange getSpecifierRange(const char *startSpecifier,
7423  unsigned specifierLen);
7424  SourceLocation getLocationOfByte(const char *x);
7425 
7426  const Expr *getDataArg(unsigned i) const;
7427 
7428  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7430  const char *startSpecifier, unsigned specifierLen,
7431  unsigned argIndex);
7432 
7433  template <typename Range>
7434  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7435  bool IsStringLocation, Range StringRange,
7436  ArrayRef<FixItHint> Fixit = None);
7437 };
7438 
7439 } // namespace
7440 
7441 SourceRange CheckFormatHandler::getFormatStringRange() {
7442  return OrigFormatExpr->getSourceRange();
7443 }
7444 
7445 CharSourceRange CheckFormatHandler::
7446 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7447  SourceLocation Start = getLocationOfByte(startSpecifier);
7448  SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7449 
7450  // Advance the end SourceLocation by one due to half-open ranges.
7451  End = End.getLocWithOffset(1);
7452 
7453  return CharSourceRange::getCharRange(Start, End);
7454 }
7455 
7456 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7457  return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7458  S.getLangOpts(), S.Context.getTargetInfo());
7459 }
7460 
7461 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7462  unsigned specifierLen){
7463  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7464  getLocationOfByte(startSpecifier),
7465  /*IsStringLocation*/true,
7466  getSpecifierRange(startSpecifier, specifierLen));
7467 }
7468 
7469 void CheckFormatHandler::HandleInvalidLengthModifier(
7472  const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7473  using namespace analyze_format_string;
7474 
7475  const LengthModifier &LM = FS.getLengthModifier();
7476  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7477 
7478  // See if we know how to fix this length modifier.
7480  if (FixedLM) {
7481  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7482  getLocationOfByte(LM.getStart()),
7483  /*IsStringLocation*/true,
7484  getSpecifierRange(startSpecifier, specifierLen));
7485 
7486  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7487  << FixedLM->toString()
7488  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7489 
7490  } else {
7491  FixItHint Hint;
7492  if (DiagID == diag::warn_format_nonsensical_length)
7493  Hint = FixItHint::CreateRemoval(LMRange);
7494 
7495  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7496  getLocationOfByte(LM.getStart()),
7497  /*IsStringLocation*/true,
7498  getSpecifierRange(startSpecifier, specifierLen),
7499  Hint);
7500  }
7501 }
7502 
7503 void CheckFormatHandler::HandleNonStandardLengthModifier(
7505  const char *startSpecifier, unsigned specifierLen) {
7506  using namespace analyze_format_string;
7507 
7508  const LengthModifier &LM = FS.getLengthModifier();
7509  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7510 
7511  // See if we know how to fix this length modifier.
7513  if (FixedLM) {
7514  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7515  << LM.toString() << 0,
7516  getLocationOfByte(LM.getStart()),
7517  /*IsStringLocation*/true,
7518  getSpecifierRange(startSpecifier, specifierLen));
7519 
7520  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7521  << FixedLM->toString()
7522  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7523 
7524  } else {
7525  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7526  << LM.toString() << 0,
7527  getLocationOfByte(LM.getStart()),
7528  /*IsStringLocation*/true,
7529  getSpecifierRange(startSpecifier, specifierLen));
7530  }
7531 }
7532 
7533 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7535  const char *startSpecifier, unsigned specifierLen) {
7536  using namespace analyze_format_string;
7537 
7538  // See if we know how to fix this conversion specifier.
7540  if (FixedCS) {
7541  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7542  << CS.toString() << /*conversion specifier*/1,
7543  getLocationOfByte(CS.getStart()),
7544  /*IsStringLocation*/true,
7545  getSpecifierRange(startSpecifier, specifierLen));
7546 
7547  CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7548  S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7549  << FixedCS->toString()
7550  << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7551  } else {
7552  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7553  << CS.toString() << /*conversion specifier*/1,
7554  getLocationOfByte(CS.getStart()),
7555  /*IsStringLocation*/true,
7556  getSpecifierRange(startSpecifier, specifierLen));
7557  }
7558 }
7559 
7560 void CheckFormatHandler::HandlePosition(const char *startPos,
7561  unsigned posLen) {
7562  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7563  getLocationOfByte(startPos),
7564  /*IsStringLocation*/true,
7565  getSpecifierRange(startPos, posLen));
7566 }
7567 
7568 void
7569 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7571  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7572  << (unsigned) p,
7573  getLocationOfByte(startPos), /*IsStringLocation*/true,
7574  getSpecifierRange(startPos, posLen));
7575 }
7576 
7577 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7578  unsigned posLen) {
7579  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7580  getLocationOfByte(startPos),
7581  /*IsStringLocation*/true,
7582  getSpecifierRange(startPos, posLen));
7583 }
7584 
7585 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7586  if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7587  // The presence of a null character is likely an error.
7588  EmitFormatDiagnostic(
7589  S.PDiag(diag::warn_printf_format_string_contains_null_char),
7590  getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7591  getFormatStringRange());
7592  }
7593 }
7594 
7595 // Note that this may return NULL if there was an error parsing or building
7596 // one of the argument expressions.
7597 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7598  return Args[FirstDataArg + i];
7599 }
7600 
7601 void CheckFormatHandler::DoneProcessing() {
7602  // Does the number of data arguments exceed the number of
7603  // format conversions in the format string?
7604  if (!HasVAListArg) {
7605  // Find any arguments that weren't covered.
7606  CoveredArgs.flip();
7607  signed notCoveredArg = CoveredArgs.find_first();
7608  if (notCoveredArg >= 0) {
7609  assert((unsigned)notCoveredArg < NumDataArgs);
7610  UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7611  } else {
7612  UncoveredArg.setAllCovered();
7613  }
7614  }
7615 }
7616 
7617 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7618  const Expr *ArgExpr) {
7619  assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7620  "Invalid state");
7621 
7622  if (!ArgExpr)
7623  return;
7624 
7625  SourceLocation Loc = ArgExpr->getBeginLoc();
7626 
7627  if (S.getSourceManager().isInSystemMacro(Loc))
7628  return;
7629 
7630  PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7631  for (auto E : DiagnosticExprs)
7632  PDiag << E->getSourceRange();
7633 
7634  CheckFormatHandler::EmitFormatDiagnostic(
7635  S, IsFunctionCall, DiagnosticExprs[0],
7636  PDiag, Loc, /*IsStringLocation*/false,
7637  DiagnosticExprs[0]->getSourceRange());
7638 }
7639 
7640 bool
7641 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7642  SourceLocation Loc,
7643  const char *startSpec,
7644  unsigned specifierLen,
7645  const char *csStart,
7646  unsigned csLen) {
7647  bool keepGoing = true;
7648  if (argIndex < NumDataArgs) {
7649  // Consider the argument coverered, even though the specifier doesn't
7650  // make sense.
7651  CoveredArgs.set(argIndex);
7652  }
7653  else {
7654  // If argIndex exceeds the number of data arguments we
7655  // don't issue a warning because that is just a cascade of warnings (and
7656  // they may have intended '%%' anyway). We don't want to continue processing
7657  // the format string after this point, however, as we will like just get
7658  // gibberish when trying to match arguments.
7659  keepGoing = false;
7660  }
7661 
7662  StringRef Specifier(csStart, csLen);
7663 
7664  // If the specifier in non-printable, it could be the first byte of a UTF-8
7665  // sequence. In that case, print the UTF-8 code point. If not, print the byte
7666  // hex value.
7667  std::string CodePointStr;
7668  if (!llvm::sys::locale::isPrint(*csStart)) {
7669  llvm::UTF32 CodePoint;
7670  const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7671  const llvm::UTF8 *E =
7672  reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7673  llvm::ConversionResult Result =
7674  llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7675 
7676  if (Result != llvm::conversionOK) {
7677  unsigned char FirstChar = *csStart;
7678  CodePoint = (llvm::UTF32)FirstChar;
7679  }
7680 
7681  llvm::raw_string_ostream OS(CodePointStr);
7682  if (CodePoint < 256)
7683  OS << "\\x" << llvm::format("%02x", CodePoint);
7684  else if (CodePoint <= 0xFFFF)
7685  OS << "\\u" << llvm::format("%04x", CodePoint);
7686  else
7687  OS << "\\U" << llvm::format("%08x", CodePoint);
7688  OS.flush();
7689  Specifier = CodePointStr;
7690  }
7691 
7692  EmitFormatDiagnostic(
7693  S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7694  /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7695 
7696  return keepGoing;
7697 }
7698 
7699 void
7700 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7701  const char *startSpec,
7702  unsigned specifierLen) {
7703  EmitFormatDiagnostic(
7704  S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7705  Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7706 }
7707 
7708 bool
7709 CheckFormatHandler::CheckNumArgs(
7712  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7713 
7714  if (argIndex >= NumDataArgs) {
7716  ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7717  << (argIndex+1) << NumDataArgs)
7718  : S.PDiag(diag::warn_printf_insufficient_data_args);
7719  EmitFormatDiagnostic(
7720  PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7721  getSpecifierRange(startSpecifier, specifierLen));
7722 
7723  // Since more arguments than conversion tokens are given, by extension
7724  // all arguments are covered, so mark this as so.
7725  UncoveredArg.setAllCovered();
7726  return false;
7727  }
7728  return true;
7729 }
7730 
7731 template<typename Range>
7732 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7733  SourceLocation Loc,
7734  bool IsStringLocation,
7735  Range StringRange,
7737  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7738  Loc, IsStringLocation, StringRange, FixIt);
7739 }
7740 
7741 /// If the format string is not within the function call, emit a note
7742 /// so that the function call and string are in diagnostic messages.
7743 ///
7744 /// \param InFunctionCall if true, the format string is within the function
7745 /// call and only one diagnostic message will be produced. Otherwise, an
7746 /// extra note will be emitted pointing to location of the format string.
7747 ///
7748 /// \param ArgumentExpr the expression that is passed as the format string
7749 /// argument in the function call. Used for getting locations when two
7750 /// diagnostics are emitted.
7751 ///
7752 /// \param PDiag the callee should already have provided any strings for the
7753 /// diagnostic message. This function only adds locations and fixits
7754 /// to diagnostics.
7755 ///
7756 /// \param Loc primary location for diagnostic. If two diagnostics are
7757 /// required, one will be at Loc and a new SourceLocation will be created for
7758 /// the other one.
7759 ///
7760 /// \param IsStringLocation if true, Loc points to the format string should be
7761 /// used for the note. Otherwise, Loc points to the argument list and will
7762 /// be used with PDiag.
7763 ///
7764 /// \param StringRange some or all of the string to highlight. This is
7765 /// templated so it can accept either a CharSourceRange or a SourceRange.
7766 ///
7767 /// \param FixIt optional fix it hint for the format string.
7768 template <typename Range>
7769 void CheckFormatHandler::EmitFormatDiagnostic(
7770  Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7771  const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7772  Range StringRange, ArrayRef<FixItHint> FixIt) {
7773  if (InFunctionCall) {
7774  const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7775  D << StringRange;
7776  D << FixIt;
7777  } else {
7778  S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7779  << ArgumentExpr->getSourceRange();
7780 
7781  const Sema::SemaDiagnosticBuilder &Note =
7782  S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7783  diag::note_format_string_defined);
7784 
7785  Note << StringRange;
7786  Note << FixIt;
7787  }
7788 }
7789 
7790 //===--- CHECK: Printf format string checking ------------------------------===//
7791 
7792 namespace {
7793 
7794 class CheckPrintfHandler : public CheckFormatHandler {
7795 public:
7796  CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7797  const Expr *origFormatExpr,
7798  const Sema::FormatStringType type, unsigned firstDataArg,
7799  unsigned numDataArgs, bool isObjC, const char *beg,
7800  bool hasVAListArg, ArrayRef<const Expr *> Args,
7801  unsigned formatIdx, bool inFunctionCall,
7802  Sema::VariadicCallType CallType,
7803  llvm::SmallBitVector &CheckedVarArgs,
7804  UncoveredArgHandler &UncoveredArg)
7805  : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7806  numDataArgs, beg, hasVAListArg, Args, formatIdx,
7807  inFunctionCall, CallType, CheckedVarArgs,
7808  UncoveredArg) {}
7809 
7810  bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7811 
7812  /// Returns true if '%@' specifiers are allowed in the format string.
7813  bool allowsObjCArg() const {
7814  return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7815  FSType == Sema::FST_OSTrace;
7816  }
7817 
7818  bool HandleInvalidPrintfConversionSpecifier(
7820  const char *startSpecifier,
7821  unsigned specifierLen) override;
7822 
7823  void handleInvalidMaskType(StringRef MaskType) override;
7824 
7825  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7826  const char *startSpecifier,
7827  unsigned specifierLen) override;
7828  bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7829  const char *StartSpecifier,
7830  unsigned SpecifierLen,
7831  const Expr *E);
7832 
7833  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7834  const char *startSpecifier, unsigned specifierLen);
7835  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7836  const analyze_printf::OptionalAmount &Amt,
7837  unsigned type,
7838  const char *startSpecifier, unsigned specifierLen);
7839  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7840  const analyze_printf::OptionalFlag &flag,
7841  const char *startSpecifier, unsigned specifierLen);
7842  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7843  const analyze_printf::OptionalFlag &ignoredFlag,
7844  const analyze_printf::OptionalFlag &flag,
7845  const char *startSpecifier, unsigned specifierLen);
7846  bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7847  const Expr *E);
7848 
7849  void HandleEmptyObjCModifierFlag(const char *startFlag,
7850  unsigned flagLen) override;
7851 
7852  void HandleInvalidObjCModifierFlag(const char *startFlag,
7853  unsigned flagLen) override;
7854 
7855  void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7856  const char *flagsEnd,
7857  const char *conversionPosition)
7858  override;
7859 };
7860 
7861 } // namespace
7862 
7863 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7865  const char *startSpecifier,
7866  unsigned specifierLen) {
7869 
7870  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7871  getLocationOfByte(CS.getStart()),
7872  startSpecifier, specifierLen,
7873  CS.getStart(), CS.getLength());
7874 }
7875 
7876 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7877  S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7878 }
7879 
7880 bool CheckPrintfHandler::HandleAmount(
7882  unsigned k, const char *startSpecifier,
7883  unsigned specifierLen) {
7884  if (Amt.hasDataArgument()) {
7885  if (!HasVAListArg) {
7886  unsigned argIndex = Amt.getArgIndex();
7887  if (argIndex >= NumDataArgs) {
7888  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7889  << k,
7890  getLocationOfByte(Amt.getStart()),
7891  /*IsStringLocation*/true,
7892  getSpecifierRange(startSpecifier, specifierLen));
7893  // Don't do any more checking. We will just emit
7894  // spurious errors.
7895  return false;
7896  }
7897 
7898  // Type check the data argument. It should be an 'int'.
7899  // Although not in conformance with C99, we also allow the argument to be
7900  // an 'unsigned int' as that is a reasonably safe case. GCC also
7901  // doesn't emit a warning for that case.
7902  CoveredArgs.set(argIndex);
7903  const Expr *Arg = getDataArg(argIndex);
7904  if (!Arg)
7905  return false;
7906 
7907  QualType T = Arg->getType();
7908 
7909  const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7910  assert(AT.isValid());
7911 
7912  if (!AT.matchesType(S.Context, T)) {
7913  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7914  << k << AT.getRepresentativeTypeName(S.Context)
7915  << T << Arg->getSourceRange(),
7916  getLocationOfByte(Amt.getStart()),
7917  /*IsStringLocation*/true,
7918  getSpecifierRange(startSpecifier, specifierLen));
7919  // Don't do any more checking. We will just emit
7920  // spurious errors.
7921  return false;
7922  }
7923  }
7924  }
7925  return true;
7926 }
7927 
7928 void CheckPrintfHandler::HandleInvalidAmount(
7930  const analyze_printf::OptionalAmount &Amt,
7931  unsigned type,
7932  const char *startSpecifier,
7933  unsigned specifierLen) {
7936 
7937  FixItHint fixit =
7939  ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7940  Amt.getConstantLength()))
7941  : FixItHint();
7942 
7943  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7944  << type << CS.toString(),
7945  getLocationOfByte(Amt.getStart()),
7946  /*IsStringLocation*/true,
7947  getSpecifierRange(startSpecifier, specifierLen),
7948  fixit);
7949 }
7950 
7951 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7952  const analyze_printf::OptionalFlag &flag,
7953  const char *startSpecifier,
7954  unsigned specifierLen) {
7955  // Warn about pointless flag with a fixit removal.
7958  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7959  << flag.toString() << CS.toString(),
7960  getLocationOfByte(flag.getPosition()),
7961  /*IsStringLocation*/true,
7962  getSpecifierRange(startSpecifier, specifierLen),
7964  getSpecifierRange(flag.getPosition(), 1)));
7965 }
7966 
7967 void CheckPrintfHandler::HandleIgnoredFlag(
7969  const analyze_printf::OptionalFlag &ignoredFlag,
7970  const analyze_printf::OptionalFlag &flag,
7971  const char *startSpecifier,
7972  unsigned specifierLen) {
7973  // Warn about ignored flag with a fixit removal.
7974  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7975  << ignoredFlag.toString() << flag.toString(),
7976  getLocationOfByte(ignoredFlag.getPosition()),
7977  /*IsStringLocation*/true,
7978  getSpecifierRange(startSpecifier, specifierLen),
7980  getSpecifierRange(ignoredFlag.getPosition(), 1)));
7981 }
7982 
7983 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7984  unsigned flagLen) {
7985  // Warn about an empty flag.
7986  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7987  getLocationOfByte(startFlag),
7988  /*IsStringLocation*/true,
7989  getSpecifierRange(startFlag, flagLen));
7990 }
7991 
7992 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7993  unsigned flagLen) {
7994  // Warn about an invalid flag.
7995  auto Range = getSpecifierRange(startFlag, flagLen);
7996  StringRef flag(startFlag, flagLen);
7997  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7998  getLocationOfByte(startFlag),
7999  /*IsStringLocation*/true,
8000  Range, FixItHint::CreateRemoval(Range));
8001 }
8002 
8003 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8004  const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8005  // Warn about using '[...]' without a '@' conversion.
8006  auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8007  auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8008  EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8009  getLocationOfByte(conversionPosition),
8010  /*IsStringLocation*/true,
8011  Range, FixItHint::CreateRemoval(Range));
8012 }
8013 
8014 // Determines if the specified is a C++ class or struct containing
8015 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8016 // "c_str()").
8017 template<typename MemberKind>
8018 static llvm::SmallPtrSet<MemberKind*, 1>
8019 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8020  const RecordType *RT = Ty->getAs<RecordType>();
8021  llvm::SmallPtrSet<MemberKind*, 1> Results;
8022 
8023  if (!RT)
8024  return Results;
8025  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8026  if (!RD || !RD->getDefinition())
8027  return Results;
8028 
8029  LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8031  R.suppressDiagnostics();
8032 
8033  // We just need to include all members of the right kind turned up by the
8034  // filter, at this point.
8035  if (S.LookupQualifiedName(R, RT->getDecl()))
8036  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8037  NamedDecl *decl = (*I)->getUnderlyingDecl();
8038  if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8039  Results.insert(FK);
8040  }
8041  return Results;
8042 }
8043 
8044 /// Check if we could call '.c_str()' on an object.
8045 ///
8046 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8047 /// allow the call, or if it would be ambiguous).
8048 bool Sema::hasCStrMethod(const Expr *E) {
8049  using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8050 
8051  MethodSet Results =
8052  CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8053  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8054  MI != ME; ++MI)
8055  if ((*MI)->getMinRequiredArguments() == 0)
8056  return true;
8057  return false;
8058 }
8059 
8060 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8061 // better diagnostic if so. AT is assumed to be valid.
8062 // Returns true when a c_str() conversion method is found.
8063 bool CheckPrintfHandler::checkForCStrMembers(
8064  const analyze_printf::ArgType &AT, const Expr *E) {
8065  using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8066 
8067  MethodSet Results =
8068  CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8069 
8070  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8071  MI != ME; ++MI) {
8072  const CXXMethodDecl *Method = *MI;
8073  if (Method->getMinRequiredArguments() == 0 &&
8074  AT.matchesType(S.Context, Method->getReturnType())) {
8075  // FIXME: Suggest parens if the expression needs them.
8076  SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8077  S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8078  << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8079  return true;
8080  }
8081  }
8082 
8083  return false;
8084 }
8085 
8086 bool
8087 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8088  &FS,
8089  const char *startSpecifier,
8090  unsigned specifierLen) {
8091  using namespace analyze_format_string;
8092  using namespace analyze_printf;
8093 
8094  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8095 
8096  if (FS.consumesDataArgument()) {
8097  if (atFirstArg) {
8098  atFirstArg = false;
8099  usesPositionalArgs = FS.usesPositionalArg();
8100  }
8101  else if (usesPositionalArgs != FS.usesPositionalArg()) {
8102  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8103  startSpecifier, specifierLen);
8104  return false;
8105  }
8106  }
8107 
8108  // First check if the field width, precision, and conversion specifier
8109  // have matching data arguments.
8110  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8111  startSpecifier, specifierLen)) {
8112  return false;
8113  }
8114 
8115  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8116  startSpecifier, specifierLen)) {
8117  return false;
8118  }
8119 
8120  if (!CS.consumesDataArgument()) {
8121  // FIXME: Technically specifying a precision or field width here
8122  // makes no sense. Worth issuing a warning at some point.
8123  return true;
8124  }
8125 
8126  // Consume the argument.
8127  unsigned argIndex = FS.getArgIndex();
8128  if (argIndex < NumDataArgs) {
8129  // The check to see if the argIndex is valid will come later.
8130  // We set the bit here because we may exit early from this
8131  // function if we encounter some other error.
8132  CoveredArgs.set(argIndex);
8133  }
8134 
8135  // FreeBSD kernel extensions.
8136  if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8137  CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8138  // We need at least two arguments.
8139  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8140  return false;
8141 
8142  // Claim the second argument.
8143  CoveredArgs.set(argIndex + 1);
8144 
8145  // Type check the first argument (int for %b, pointer for %D)
8146  const Expr *Ex = getDataArg(argIndex);
8147  const analyze_printf::ArgType &AT =
8148  (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8149  ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8150  if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8151  EmitFormatDiagnostic(
8152  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8153  << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8154  << false << Ex->getSourceRange(),
8155  Ex->getBeginLoc(), /*IsStringLocation*/ false,
8156  getSpecifierRange(startSpecifier, specifierLen));
8157 
8158  // Type check the second argument (char * for both %b and %D)
8159  Ex = getDataArg(argIndex + 1);
8160  const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8161  if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8162  EmitFormatDiagnostic(
8163  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8164  << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8165  << false << Ex->getSourceRange(),
8166  Ex->getBeginLoc(), /*IsStringLocation*/ false,
8167  getSpecifierRange(startSpecifier, specifierLen));
8168 
8169  return true;
8170  }
8171 
8172  // Check for using an Objective-C specific conversion specifier
8173  // in a non-ObjC literal.
8174  if (!allowsObjCArg() && CS.isObjCArg()) {
8175  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8176  specifierLen);
8177  }
8178 
8179  // %P can only be used with os_log.
8180  if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8181  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8182  specifierLen);
8183  }
8184 
8185  // %n is not allowed with os_log.
8186  if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8187  EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8188  getLocationOfByte(CS.getStart()),
8189  /*IsStringLocation*/ false,
8190  getSpecifierRange(startSpecifier, specifierLen));
8191 
8192  return true;
8193  }
8194 
8195  // Only scalars are allowed for os_trace.
8196  if (FSType == Sema::FST_OSTrace &&
8197  (CS.getKind() == ConversionSpecifier::PArg ||
8198  CS.getKind() == ConversionSpecifier::sArg ||
8199  CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8200  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8201  specifierLen);
8202  }
8203 
8204  // Check for use of public/private annotation outside of os_log().
8205  if (FSType != Sema::FST_OSLog) {
8206  if (FS.isPublic().isSet()) {
8207  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8208  << "public",
8209  getLocationOfByte(FS.isPublic().getPosition()),
8210  /*IsStringLocation*/ false,
8211  getSpecifierRange(startSpecifier, specifierLen));
8212  }
8213  if (FS.isPrivate().isSet()) {
8214  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8215  << "private",
8216  getLocationOfByte(FS.isPrivate().getPosition()),
8217  /*IsStringLocation*/ false,
8218  getSpecifierRange(startSpecifier, specifierLen));
8219  }
8220  }
8221 
8222  // Check for invalid use of field width
8223  if (!FS.hasValidFieldWidth()) {
8224  HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8225  startSpecifier, specifierLen);
8226  }
8227 
8228  // Check for invalid use of precision
8229  if (!FS.hasValidPrecision()) {
8230  HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8231  startSpecifier, specifierLen);
8232  }
8233 
8234  // Precision is mandatory for %P specifier.
8235  if (CS.getKind() == ConversionSpecifier::PArg &&
8236  FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8237  EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8238  getLocationOfByte(startSpecifier),
8239  /*IsStringLocation*/ false,
8240  getSpecifierRange(startSpecifier, specifierLen));
8241  }
8242 
8243  // Check each flag does not conflict with any other component.
8245  HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8246  if (!FS.hasValidLeadingZeros())
8247  HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8248  if (!FS.hasValidPlusPrefix())
8249  HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8250  if (!FS.hasValidSpacePrefix())
8251  HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8252  if (!FS.hasValidAlternativeForm())
8253  HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8254  if (!FS.hasValidLeftJustified())
8255  HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8256 
8257  // Check that flags are not ignored by another flag
8258  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8259  HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8260  startSpecifier, specifierLen);
8261  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8262  HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8263  startSpecifier, specifierLen);
8264 
8265  // Check the length modifier is valid with the given conversion specifier.
8267  S.getLangOpts()))
8268  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8269  diag::warn_format_nonsensical_length);
8270  else if (!FS.hasStandardLengthModifier())
8271  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8273  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8274  diag::warn_format_non_standard_conversion_spec);
8275 
8277  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8278 
8279  // The remaining checks depend on the data arguments.
8280  if (HasVAListArg)
8281  return true;
8282 
8283  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8284  return false;
8285 
8286  const Expr *Arg = getDataArg(argIndex);
8287  if (!Arg)
8288  return true;
8289 
8290  return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8291 }
8292 
8293 static bool requiresParensToAddCast(const Expr *E) {
8294  // FIXME: We should have a general way to reason about operator
8295  // precedence and whether parens are actually needed here.
8296  // Take care of a few common cases where they aren't.
8297  const Expr *Inside = E->IgnoreImpCasts();
8298  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8299  Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8300 
8301  switch (Inside->getStmtClass()) {
8302  case Stmt::ArraySubscriptExprClass:
8303  case Stmt::CallExprClass:
8304  case Stmt::CharacterLiteralClass:
8305  case Stmt::CXXBoolLiteralExprClass:
8306  case Stmt::DeclRefExprClass:
8307  case Stmt::FloatingLiteralClass:
8308  case Stmt::IntegerLiteralClass:
8309  case Stmt::MemberExprClass:
8310  case Stmt::ObjCArrayLiteralClass:
8311  case Stmt::ObjCBoolLiteralExprClass:
8312  case Stmt::ObjCBoxedExprClass:
8313  case Stmt::ObjCDictionaryLiteralClass:
8314  case Stmt::ObjCEncodeExprClass:
8315  case Stmt::ObjCIvarRefExprClass:
8316  case Stmt::ObjCMessageExprClass:
8317  case Stmt::ObjCPropertyRefExprClass:
8318  case Stmt::ObjCStringLiteralClass:
8319  case Stmt::ObjCSubscriptRefExprClass:
8320  case Stmt::ParenExprClass:
8321  case Stmt::StringLiteralClass:
8322  case Stmt::UnaryOperatorClass:
8323  return false;
8324  default:
8325  return true;
8326  }
8327 }
8328 
8329 static std::pair<QualType, StringRef>
8331  QualType IntendedTy,
8332  const Expr *E) {
8333  // Use a 'while' to peel off layers of typedefs.
8334  QualType TyTy = IntendedTy;
8335  while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8336  StringRef Name = UserTy->getDecl()->getName();
8337  QualType CastTy = llvm::StringSwitch<QualType>(Name)
8338  .Case("CFIndex", Context.getNSIntegerType())
8339  .Case("NSInteger", Context.getNSIntegerType())
8340  .Case("NSUInteger", Context.getNSUIntegerType())
8341  .Case("SInt32", Context.IntTy)
8342  .Case("UInt32", Context.UnsignedIntTy)
8343  .Default(QualType());
8344 
8345  if (!CastTy.isNull())
8346  return std::make_pair(CastTy, Name);
8347 
8348  TyTy = UserTy->desugar();
8349  }
8350 
8351  // Strip parens if necessary.
8352  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8353  return shouldNotPrintDirectly(Context,
8354  PE->getSubExpr()->getType(),
8355  PE->getSubExpr());
8356 
8357  // If this is a conditional expression, then its result type is constructed
8358  // via usual arithmetic conversions and thus there might be no necessary
8359  // typedef sugar there. Recurse to operands to check for NSInteger &
8360  // Co. usage condition.
8361  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8362  QualType TrueTy, FalseTy;
8363  StringRef TrueName, FalseName;
8364 
8365  std::tie(TrueTy, TrueName) =
8366  shouldNotPrintDirectly(Context,
8367  CO->getTrueExpr()->getType(),
8368  CO->getTrueExpr());
8369  std::tie(FalseTy, FalseName) =
8370  shouldNotPrintDirectly(Context,
8371  CO->getFalseExpr()->getType(),
8372  CO->getFalseExpr());
8373 
8374  if (TrueTy == FalseTy)
8375  return std::make_pair(TrueTy, TrueName);
8376  else if (TrueTy.isNull())
8377  return std::make_pair(FalseTy, FalseName);
8378  else if (FalseTy.isNull())
8379  return std::make_pair(TrueTy, TrueName);
8380  }
8381 
8382  return std::make_pair(QualType(), StringRef());
8383 }
8384 
8385 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8386 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8387 /// type do not count.
8388 static bool
8390  QualType From = ICE->getSubExpr()->getType();
8391  QualType To = ICE->getType();
8392  // It's an integer promotion if the destination type is the promoted
8393  // source type.
8394  if (ICE->getCastKind() == CK_IntegralCast &&
8395  From->isPromotableIntegerType() &&
8396  S.Context.getPromotedIntegerType(From) == To)
8397  return true;
8398  // Look through vector types, since we do default argument promotion for
8399  // those in OpenCL.
8400  if (const auto *VecTy = From->getAs<ExtVectorType>())
8401  From = VecTy->getElementType();
8402  if (const auto *VecTy = To->getAs<ExtVectorType>())
8403  To = VecTy->getElementType();
8404  // It's a floating promotion if the source type is a lower rank.
8405  return ICE->getCastKind() == CK_FloatingCast &&
8406  S.Context.getFloatingTypeOrder(From, To) < 0;
8407 }
8408 
8409 bool
8410 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8411  const char *StartSpecifier,
8412  unsigned SpecifierLen,
8413  const Expr *E) {
8414  using namespace analyze_format_string;
8415  using namespace analyze_printf;
8416 
8417  // Now type check the data expression that matches the
8418  // format specifier.
8419  const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8420  if (!AT.isValid())
8421  return true;
8422 
8423  QualType ExprTy = E->getType();
8424  while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8425  ExprTy = TET->getUnderlyingExpr()->getType();
8426  }
8427 
8428  // Diagnose attempts to print a boolean value as a character. Unlike other
8429  // -Wformat diagnostics, this is fine from a type perspective, but it still
8430  // doesn't make sense.
8431  if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8433  const CharSourceRange &CSR =
8434  getSpecifierRange(StartSpecifier, SpecifierLen);
8435  SmallString<4> FSString;
8436  llvm::raw_svector_ostream os(FSString);
8437  FS.toString(os);
8438  EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8439  << FSString,
8440  E->getExprLoc(), false, CSR);
8441  return true;
8442  }
8443 
8444  analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8445  if (Match == analyze_printf::ArgType::Match)
8446  return true;
8447 
8448  // Look through argument promotions for our error message's reported type.
8449  // This includes the integral and floating promotions, but excludes array
8450  // and function pointer decay (seeing that an argument intended to be a
8451  // string has type 'char [6]' is probably more confusing than 'char *') and
8452  // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8453  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8454  if (isArithmeticArgumentPromotion(S, ICE)) {
8455  E = ICE->getSubExpr();
8456  ExprTy = E->getType();
8457 
8458  // Check if we didn't match because of an implicit cast from a 'char'
8459  // or 'short' to an 'int'. This is done because printf is a varargs
8460  // function.
8461  if (ICE->getType() == S.Context.IntTy ||
8462  ICE->getType() == S.Context.UnsignedIntTy) {
8463  // All further checking is done on the subexpression
8464  const analyze_printf::ArgType::MatchKind ImplicitMatch =
8465  AT.matchesType(S.Context, ExprTy);
8466  if (ImplicitMatch == analyze_printf::ArgType::Match)
8467  return true;
8468  if (ImplicitMatch == ArgType::NoMatchPedantic ||
8469  ImplicitMatch == ArgType::NoMatchTypeConfusion)
8470  Match = ImplicitMatch;
8471  }
8472  }
8473  } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8474  // Special case for 'a', which has type 'int' in C.
8475  // Note, however, that we do /not/ want to treat multibyte constants like
8476  // 'MooV' as characters! This form is deprecated but still exists.
8477  if (ExprTy == S.Context.IntTy)
8478  if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8479  ExprTy = S.Context.CharTy;
8480  }
8481 
8482  // Look through enums to their underlying type.
8483  bool IsEnum = false;
8484  if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8485  ExprTy = EnumTy->getDecl()->getIntegerType();
8486  IsEnum = true;
8487  }
8488 
8489  // %C in an Objective-C context prints a unichar, not a wchar_t.
8490  // If the argument is an integer of some kind, believe the %C and suggest
8491  // a cast instead of changing the conversion specifier.
8492  QualType IntendedTy = ExprTy;
8493  if (isObjCContext() &&
8494  FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8495  if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8496  !ExprTy->isCharType()) {
8497  // 'unichar' is defined as a typedef of unsigned short, but we should
8498  // prefer using the typedef if it is visible.
8499  IntendedTy = S.Context.UnsignedShortTy;
8500 
8501  // While we are here, check if the value is an IntegerLiteral that happens
8502  // to be within the valid range.
8503  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8504  const llvm::APInt &V = IL->getValue();
8505  if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8506  return true;
8507  }
8508 
8509  LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8511  if (S.LookupName(Result, S.getCurScope())) {
8512  NamedDecl *ND = Result.getFoundDecl();
8513  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8514  if (TD->getUnderlyingType() == IntendedTy)
8515  IntendedTy = S.Context.getTypedefType(TD);
8516  }
8517  }
8518  }
8519 
8520  // Special-case some of Darwin's platform-independence types by suggesting
8521  // casts to primitive types that are known to be large enough.
8522  bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8523  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8524  QualType CastTy;
8525  std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8526  if (!CastTy.isNull()) {
8527  // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8528  // (long in ASTContext). Only complain to pedants.
8529  if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8530  (AT.isSizeT() || AT.isPtrdiffT()) &&
8531  AT.matchesType(S.Context, CastTy))
8532  Match = ArgType::NoMatchPedantic;
8533  IntendedTy = CastTy;
8534  ShouldNotPrintDirectly = true;
8535  }
8536  }
8537 
8538  // We may be able to offer a FixItHint if it is a supported type.
8539  PrintfSpecifier fixedFS = FS;
8540  bool Success =
8541  fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8542 
8543  if (Success) {
8544  // Get the fix string from the fixed format specifier
8545  SmallString<16> buf;
8546  llvm::raw_svector_ostream os(buf);
8547  fixedFS.toString(os);
8548 
8549  CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8550 
8551  if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8552  unsigned Diag;
8553  switch (Match) {
8554  case ArgType::Match: llvm_unreachable("expected non-matching");
8555  case ArgType::NoMatchPedantic:
8556  Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8557  break;
8558  case ArgType::NoMatchTypeConfusion:
8559  Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8560  break;
8561  case ArgType::NoMatch:
8562  Diag = diag::warn_format_conversion_argument_type_mismatch;
8563  break;
8564  }
8565 
8566  // In this case, the specifier is wrong and should be changed to match
8567  // the argument.
8568  EmitFormatDiagnostic(S.PDiag(Diag)
8569  << AT.getRepresentativeTypeName(S.Context)
8570  << IntendedTy << IsEnum << E->getSourceRange(),
8571  E->getBeginLoc(),
8572  /*IsStringLocation*/ false, SpecRange,
8573  FixItHint::CreateReplacement(SpecRange, os.str()));
8574  } else {
8575  // The canonical type for formatting this value is different from the
8576  // actual type of the expression. (This occurs, for example, with Darwin's
8577  // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8578  // should be printed as 'long' for 64-bit compatibility.)
8579  // Rather than emitting a normal format/argument mismatch, we want to
8580  // add a cast to the recommended type (and correct the format string
8581  // if necessary).
8582  SmallString<16> CastBuf;
8583  llvm::raw_svector_ostream CastFix(CastBuf);
8584  CastFix << "(";
8585  IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8586  CastFix << ")";
8587 
8589  if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8590  Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8591 
8592  if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8593  // If there's already a cast present, just replace it.
8594  SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8595  Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8596 
8597  } else if (!requiresParensToAddCast(E)) {
8598  // If the expression has high enough precedence,
8599  // just write the C-style cast.
8600  Hints.push_back(
8601  FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8602  } else {
8603  // Otherwise, add parens around the expression as well as the cast.
8604  CastFix << "(";
8605  Hints.push_back(
8606  FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8607 
8609  Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8610  }
8611 
8612  if (ShouldNotPrintDirectly) {
8613  // The expression has a type that should not be printed directly.
8614  // We extract the name from the typedef because we don't want to show
8615  // the underlying type in the diagnostic.
8616  StringRef Name;
8617  if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8618  Name = TypedefTy->getDecl()->getName();
8619  else
8620  Name = CastTyName;
8621  unsigned Diag = Match == ArgType::NoMatchPedantic
8622  ? diag::warn_format_argument_needs_cast_pedantic
8623  : diag::warn_format_argument_needs_cast;
8624  EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8625  << E->getSourceRange(),
8626  E->getBeginLoc(), /*IsStringLocation=*/false,
8627  SpecRange, Hints);
8628  } else {
8629  // In this case, the expression could be printed using a different
8630  // specifier, but we've decided that the specifier is probably correct
8631  // and we should cast instead. Just use the normal warning message.
8632  EmitFormatDiagnostic(
8633  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8634  << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8635  << E->getSourceRange(),
8636  E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8637  }
8638  }
8639  } else {
8640  const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8641  SpecifierLen);
8642  // Since the warning for passing non-POD types to variadic functions
8643  // was deferred until now, we emit a warning for non-POD
8644  // arguments here.
8645  switch (S.isValidVarArgType(ExprTy)) {
8646  case Sema::VAK_Valid:
8647  case Sema::VAK_ValidInCXX11: {
8648  unsigned Diag;
8649  switch (Match) {
8650  case ArgType::Match: llvm_unreachable("expected non-matching");
8651  case ArgType::NoMatchPedantic:
8652  Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8653  break;
8654  case ArgType::NoMatchTypeConfusion:
8655  Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8656  break;
8657  case ArgType::NoMatch:
8658  Diag = diag::warn_format_conversion_argument_type_mismatch;
8659  break;
8660  }
8661 
8662  EmitFormatDiagnostic(
8663  S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8664  << IsEnum << CSR << E->getSourceRange(),
8665  E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8666  break;
8667  }
8668  case Sema::VAK_Undefined:
8670  EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8671  << S.getLangOpts().CPlusPlus11 << ExprTy
8672  << CallType
8673  << AT.getRepresentativeTypeName(S.Context) << CSR
8674  << E->getSourceRange(),
8675  E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8676  checkForCStrMembers(AT, E);
8677  break;
8678 
8679  case Sema::VAK_Invalid:
8680  if (ExprTy->isObjCObjectType())
8681  EmitFormatDiagnostic(
8682  S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8683  << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8684  << AT.getRepresentativeTypeName(S.Context) << CSR
8685  << E->getSourceRange(),
8686  E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8687  else
8688  // FIXME: If this is an initializer list, suggest removing the braces
8689  // or inserting a cast to the target type.
8690  S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8691  << isa<InitListExpr>(E) << ExprTy << CallType
8692  << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8693  break;
8694  }
8695 
8696  assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8697  "format string specifier index out of range");
8698  CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8699  }
8700 
8701  return true;
8702 }
8703 
8704 //===--- CHECK: Scanf format string checking ------------------------------===//
8705 
8706 namespace {
8707 
8708 class CheckScanfHandler : public CheckFormatHandler {
8709 public:
8710  CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8711  const Expr *origFormatExpr, Sema::FormatStringType type,
8712  unsigned firstDataArg, unsigned numDataArgs,
8713  const char *beg, bool hasVAListArg,
8714  ArrayRef<const Expr *> Args, unsigned formatIdx,
8715  bool inFunctionCall, Sema::VariadicCallType CallType,
8716  llvm::SmallBitVector &CheckedVarArgs,
8717  UncoveredArgHandler &UncoveredArg)
8718  : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8719  numDataArgs, beg, hasVAListArg, Args, formatIdx,
8720  inFunctionCall, CallType, CheckedVarArgs,
8721  UncoveredArg) {}
8722 
8723  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8724  const char *startSpecifier,
8725  unsigned specifierLen) override;
8726 
8727  bool HandleInvalidScanfConversionSpecifier(
8729  const char *startSpecifier,
8730  unsigned specifierLen) override;
8731 
8732  void HandleIncompleteScanList(const char *start, const char *end) override;
8733 };
8734 
8735 } // namespace
8736 
8737 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8738  const char *end) {
8739  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8740  getLocationOfByte(end), /*IsStringLocation*/true,
8741  getSpecifierRange(start, end - start));
8742 }
8743 
8744 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8746  const char *startSpecifier,
8747  unsigned specifierLen) {
8750 
8751  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8752  getLocationOfByte(CS.getStart()),
8753  startSpecifier, specifierLen,
8754  CS.getStart(), CS.getLength());
8755 }
8756 
8757 bool CheckScanfHandler::HandleScanfSpecifier(
8759  const char *startSpecifier,
8760  unsigned specifierLen) {
8761  using namespace analyze_scanf;
8762  using namespace analyze_format_string;
8763 
8764  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8765 
8766  // Handle case where '%' and '*' don't consume an argument. These shouldn't
8767  // be used to decide if we are using positional arguments consistently.
8768  if (FS.consumesDataArgument()) {
8769  if (atFirstArg) {
8770  atFirstArg = false;
8771  usesPositionalArgs = FS.usesPositionalArg();
8772  }
8773  else if (usesPositionalArgs != FS.usesPositionalArg()) {
8774  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8775  startSpecifier, specifierLen);
8776  return false;
8777  }
8778  }
8779 
8780  // Check if the field with is non-zero.
8781  const OptionalAmount &Amt = FS.getFieldWidth();
8782  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8783  if (Amt.getConstantAmount() == 0) {
8784  const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8785  Amt.getConstantLength());
8786  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8787  getLocationOfByte(Amt.getStart()),
8788  /*IsStringLocation*/true, R,
8790  }
8791  }
8792 
8793  if (!FS.consumesDataArgument()) {
8794  // FIXME: Technically specifying a precision or field width here
8795  // makes no sense. Worth issuing a warning at some point.
8796  return true;
8797  }
8798 
8799  // Consume the argument.
8800  unsigned argIndex = FS.getArgIndex();
8801  if (argIndex < NumDataArgs) {
8802  // The check to see if the argIndex is valid will come later.
8803  // We set the bit here because we may exit early from this
8804  // function if we encounter some other error.
8805  CoveredArgs.set(argIndex);
8806  }
8807 
8808  // Check the length modifier is valid with the given conversion specifier.
8810  S.getLangOpts()))
8811  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8812  diag::warn_format_nonsensical_length);
8813  else if (!FS.hasStandardLengthModifier())
8814  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8816  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8817  diag::warn_format_non_standard_conversion_spec);
8818 
8820  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8821 
8822  // The remaining checks depend on the data arguments.
8823  if (HasVAListArg)
8824  return true;
8825 
8826  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8827  return false;
8828 
8829  // Check that the argument type matches the format specifier.
8830  const Expr *Ex = getDataArg(argIndex);
8831  if (!Ex)
8832  return true;
8833 
8835 
8836  if (!AT.isValid()) {
8837  return true;
8838  }
8839 
8841  AT.matchesType(S.Context, Ex->getType());
8842  bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8844  return true;
8845 
8846  ScanfSpecifier fixedFS = FS;
8847  bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8848  S.getLangOpts(), S.Context);
8849 
8850  unsigned Diag =
8851  Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8852  : diag::warn_format_conversion_argument_type_mismatch;
8853 
8854  if (Success) {
8855  // Get the fix string from the fixed format specifier.
8856  SmallString<128> buf;
8857  llvm::raw_svector_ostream os(buf);
8858  fixedFS.toString(os);
8859 
8860  EmitFormatDiagnostic(
8861  S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8862  << Ex->getType() << false << Ex->getSourceRange(),
8863  Ex->getBeginLoc(),
8864  /*IsStringLocation*/ false,
8865  getSpecifierRange(startSpecifier, specifierLen),
8867  getSpecifierRange(startSpecifier, specifierLen), os.str()));
8868  } else {
8869  EmitFormatDiagnostic(S.PDiag(Diag)
8871  << Ex->getType() << false << Ex->getSourceRange(),
8872  Ex->getBeginLoc(),
8873  /*IsStringLocation*/ false,
8874  getSpecifierRange(startSpecifier, specifierLen));
8875  }
8876 
8877  return true;
8878 }
8879 
8880 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8881  const Expr *OrigFormatExpr,
8882  ArrayRef<const Expr *> Args,
8883  bool HasVAListArg, unsigned format_idx,
8884  unsigned firstDataArg,
8886  bool inFunctionCall,
8887  Sema::VariadicCallType CallType,
8888  llvm::SmallBitVector &CheckedVarArgs,
8889  UncoveredArgHandler &UncoveredArg,
8890  bool IgnoreStringsWithoutSpecifiers) {
8891  // CHECK: is the format string a wide literal?
8892  if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8893  CheckFormatHandler::EmitFormatDiagnostic(
8894  S, inFunctionCall, Args[format_idx],
8895  S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8896  /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8897  return;
8898  }
8899 
8900  // Str - The format string. NOTE: this is NOT null-terminated!
8901  StringRef StrRef = FExpr->getString();
8902  const char *Str = StrRef.data();
8903  // Account for cases where the string literal is truncated in a declaration.
8904  const ConstantArrayType *T =
8905  S.Context.getAsConstantArrayType(FExpr->getType());
8906  assert(T && "String literal not of constant array type!");
8907  size_t TypeSize = T->getSize().getZExtValue();
8908  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8909  const unsigned numDataArgs = Args.size() - firstDataArg;
8910 
8911  if (IgnoreStringsWithoutSpecifiers &&
8913  Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8914  return;
8915 
8916  // Emit a warning if the string literal is truncated and does not contain an
8917  // embedded null character.
8918  if (TypeSize <= StrRef.size() &&
8919  StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8920  CheckFormatHandler::EmitFormatDiagnostic(
8921  S, inFunctionCall, Args[format_idx],
8922  S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8923  FExpr->getBeginLoc(),
8924  /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8925  return;
8926  }
8927 
8928  // CHECK: empty format string?
8929  if (StrLen == 0 && numDataArgs > 0) {
8930  CheckFormatHandler::EmitFormatDiagnostic(
8931  S, inFunctionCall, Args[format_idx],
8932  S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8933  /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8934  return;
8935  }
8936 
8937  if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8938  Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8939  Type == Sema::FST_OSTrace) {
8940  CheckPrintfHandler H(
8941  S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8942  (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8943  HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8944  CheckedVarArgs, UncoveredArg);
8945 
8946  if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8947  S.getLangOpts(),
8948  S.Context.getTargetInfo(),
8949  Type == Sema::FST_FreeBSDKPrintf))
8950  H.DoneProcessing();
8951  } else if (Type == Sema::FST_Scanf) {
8952  CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8953  numDataArgs, Str, HasVAListArg, Args, format_idx,
8954  inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8955 
8956  if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8957  S.getLangOpts(),
8958  S.Context.getTargetInfo()))
8959  H.DoneProcessing();
8960  } // TODO: handle other formats
8961 }
8962 
8964  // Str - The format string. NOTE: this is NOT null-terminated!
8965  StringRef StrRef = FExpr->getString();
8966  const char *Str = StrRef.data();
8967  // Account for cases where the string literal is truncated in a declaration.
8968  const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8969  assert(T && "String literal not of constant array type!");
8970  size_t TypeSize = T->getSize().getZExtValue();
8971  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8972  return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8973  getLangOpts(),
8974  Context.getTargetInfo());
8975 }
8976 
8977 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8978 
8979 // Returns the related absolute value function that is larger, of 0 if one
8980 // does not exist.
8981 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8982  switch (AbsFunction) {
8983  default:
8984  return 0;
8985 
8986  case Builtin::BI__builtin_abs:
8987  return Builtin::BI__builtin_labs;
8988  case Builtin::BI__builtin_labs:
8989  return Builtin::BI__builtin_llabs;
8990  case Builtin::BI__builtin_llabs:
8991  return 0;
8992 
8993  case Builtin::BI__builtin_fabsf:
8994  return Builtin::BI__builtin_fabs;
8995  case Builtin::BI__builtin_fabs:
8996  return Builtin::BI__builtin_fabsl;
8997  case Builtin::BI__builtin_fabsl:
8998  return 0;
8999 
9000  case Builtin::BI__builtin_cabsf:
9001  return Builtin::BI__builtin_cabs;
9002  case Builtin::BI__builtin_cabs:
9003  return Builtin::BI__builtin_cabsl;
9004  case Builtin::BI__builtin_cabsl:
9005  return 0;
9006 
9007  case Builtin::BIabs:
9008  return Builtin::BIlabs;
9009  case Builtin::BIlabs:
9010  return Builtin::BIllabs;
9011  case Builtin::BIllabs:
9012  return 0;
9013 
9014  case Builtin::BIfabsf:
9015  return Builtin::BIfabs;
9016  case Builtin::BIfabs:
9017  return Builtin::BIfabsl;
9018  case Builtin::BIfabsl:
9019  return 0;
9020 
9021  case Builtin::BIcabsf:
9022  return Builtin::BIcabs;
9023  case Builtin::BIcabs:
9024  return Builtin::BIcabsl;
9025  case Builtin::BIcabsl:
9026  return 0;
9027  }
9028 }
9029 
9030 // Returns the argument type of the absolute value function.
9032  unsigned AbsType) {
9033  if (AbsType == 0)
9034  return QualType();
9035 
9037  QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9038  if (Error != ASTContext::GE_None)
9039  return QualType();
9040 
9041  const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9042  if (!FT)
9043  return QualType();
9044 
9045  if (FT->getNumParams() != 1)
9046  return QualType();
9047 
9048  return FT->getParamType(0);
9049 }
9050 
9051 // Returns the best absolute value function, or zero, based on type and
9052 // current absolute value function.
9053 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9054  unsigned AbsFunctionKind) {
9055  unsigned BestKind = 0;
9056  uint64_t ArgSize = Context.getTypeSize(ArgType);
9057  for (unsigned Kind = AbsFunctionKind; Kind != 0;
9059  QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9060  if (Context.getTypeSize(ParamType) >= ArgSize) {
9061  if (BestKind == 0)
9062  BestKind = Kind;
9063  else if (Context.hasSameType(ParamType, ArgType)) {
9064  BestKind = Kind;
9065  break;
9066  }
9067  }
9068  }
9069  return BestKind;
9070 }
9071 
9076 };
9077 
9079  if (T->isIntegralOrEnumerationType())
9080  return AVK_Integer;
9081  if (T->isRealFloatingType())
9082  return AVK_Floating;
9083  if (T->isAnyComplexType())
9084  return AVK_Complex;
9085 
9086  llvm_unreachable("Type not integer, floating, or complex");
9087 }
9088 
9089 // Changes the absolute value function to a different type. Preserves whether
9090 // the function is a builtin.
9091 static unsigned changeAbsFunction(unsigned AbsKind,
9092  AbsoluteValueKind ValueKind) {
9093  switch (ValueKind) {
9094  case AVK_Integer:
9095  switch (AbsKind) {
9096  default:
9097  return 0;
9098  case Builtin::BI__builtin_fabsf:
9099  case Builtin::BI__builtin_fabs:
9100  case Builtin::BI__builtin_fabsl:
9101  case Builtin::BI__builtin_cabsf:
9102  case Builtin::BI__builtin_cabs:
9103  case Builtin::BI__builtin_cabsl:
9104  return Builtin::BI__builtin_abs;
9105  case Builtin::BIfabsf:
9106  case Builtin::BIfabs:
9107  case Builtin::BIfabsl:
9108  case Builtin::BIcabsf:
9109  case Builtin::BIcabs:
9110  case Builtin::BIcabsl:
9111  return Builtin::BIabs;
9112  }
9113  case AVK_Floating:
9114  switch (AbsKind) {
9115  default:
9116  return 0;
9117  case Builtin::BI__builtin_abs:
9118  case Builtin::BI__builtin_labs:
9119  case Builtin::BI__builtin_llabs:
9120  case Builtin::BI__builtin_cabsf:
9121  case Builtin::BI__builtin_cabs:
9122  case Builtin::BI__builtin_cabsl:
9123  return Builtin::BI__builtin_fabsf;
9124  case Builtin::BIabs:
9125  case Builtin::BIlabs:
9126  case Builtin::BIllabs:
9127  case Builtin::BIcabsf:
9128  case Builtin::BIcabs:
9129  case Builtin::BIcabsl:
9130  return Builtin::BIfabsf;
9131  }
9132  case AVK_Complex:
9133  switch (AbsKind) {
9134  default:
9135  return 0;
9136  case Builtin::BI__builtin_abs:
9137  case Builtin::BI__builtin_labs:
9138  case Builtin::BI__builtin_llabs:
9139  case Builtin::BI__builtin_fabsf:
9140  case Builtin::BI__builtin_fabs:
9141  case Builtin::BI__builtin_fabsl:
9142  return Builtin::BI__builtin_cabsf;
9143  case Builtin::BIabs:
9144  case Builtin::BIlabs:
9145  case Builtin::BIllabs:
9146  case Builtin::BIfabsf:
9147  case Builtin::BIfabs:
9148  case Builtin::BIfabsl:
9149  return Builtin::BIcabsf;
9150  }
9151  }
9152  llvm_unreachable("Unable to convert function");
9153 }
9154 
9155 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9156  const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9157  if (!FnInfo)
9158  return 0;
9159 
9160  switch (FDecl->getBuiltinID()) {
9161  default:
9162  return 0;
9163  case Builtin::BI__builtin_abs:
9164  case Builtin::BI__builtin_fabs:
9165  case Builtin::BI__builtin_fabsf:
9166  case Builtin::BI__builtin_fabsl:
9167  case Builtin::BI__builtin_labs:
9168  case Builtin::BI__builtin_llabs:
9169  case Builtin::BI__builtin_cabs:
9170  case Builtin::BI__builtin_cabsf:
9171  case Builtin::BI__builtin_cabsl:
9172  case Builtin::BIabs:
9173  case Builtin::BIlabs:
9174  case Builtin::BIllabs:
9175  case Builtin::BIfabs:
9176  case Builtin::BIfabsf:
9177  case Builtin::BIfabsl:
9178  case Builtin::BIcabs:
9179  case Builtin::BIcabsf:
9180  case Builtin::BIcabsl:
9181  return FDecl->getBuiltinID();
9182  }
9183  llvm_unreachable("Unknown Builtin type");
9184 }
9185 
9186 // If the replacement is valid, emit a note with replacement function.
9187 // Additionally, suggest including the proper header if not already included.
9188 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9189  unsigned AbsKind, QualType ArgType) {
9190  bool EmitHeaderHint = true;
9191  const char *HeaderName = nullptr;
9192  const char *FunctionName = nullptr;
9193  if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9194  FunctionName = "std::abs";
9195  if (ArgType->isIntegralOrEnumerationType()) {
9196  HeaderName = "cstdlib";
9197  } else if (ArgType->isRealFloatingType()) {
9198  HeaderName = "cmath";
9199  } else {
9200  llvm_unreachable("Invalid Type");
9201  }
9202 
9203  // Lookup all std::abs
9204  if (NamespaceDecl *Std = S.getStdNamespace()) {
9205  LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9206  R.suppressDiagnostics();
9207  S.LookupQualifiedName(R, Std);
9208 
9209  for (const auto *I : R) {
9210  const FunctionDecl *FDecl = nullptr;
9211  if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9212  FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9213  } else {
9214  FDecl = dyn_cast<FunctionDecl>(I);
9215  }
9216  if (!FDecl)
9217  continue;
9218 
9219  // Found std::abs(), check that they are the right ones.
9220  if (FDecl->getNumParams() != 1)
9221  continue;
9222 
9223  // Check that the parameter type can handle the argument.
9224  QualType ParamType = FDecl->getParamDecl(0)->getType();
9225  if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9226  S.Context.getTypeSize(ArgType) <=
9227  S.Context.getTypeSize(ParamType)) {
9228  // Found a function, don't need the header hint.
9229  EmitHeaderHint = false;
9230  break;
9231  }
9232  }
9233  }
9234  } else {
9235  FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9236  HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9237 
9238  if (HeaderName) {
9239  DeclarationName DN(&S.Context.Idents.get(FunctionName));
9240  LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9241  R.suppressDiagnostics();
9242  S.LookupName(R, S.getCurScope());
9243 
9244  if (R.isSingleResult()) {
9245  FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9246  if (FD && FD->getBuiltinID() == AbsKind) {
9247  EmitHeaderHint = false;
9248  } else {
9249  return;
9250  }
9251  } else if (!R.empty()) {
9252  return;
9253  }
9254  }
9255  }
9256 
9257  S.Diag(Loc, diag::note_replace_abs_function)
9258  << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9259 
9260  if (!HeaderName)
9261  return;
9262 
9263  if (!EmitHeaderHint)
9264  return;
9265 
9266  S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9267  << FunctionName;
9268 }
9269 
9270 template <std::size_t StrLen>
9271 static bool IsStdFunction(const FunctionDecl *FDecl,
9272  const char (&Str)[StrLen]) {
9273  if (!FDecl)
9274  return false;
9275  if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9276  return false;
9277  if (!FDecl->isInStdNamespace())
9278  return false;
9279 
9280  return true;
9281 }
9282 
9283 // Warn when using the wrong abs() function.
9284 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9285  const FunctionDecl *FDecl) {
9286  if (Call->getNumArgs() != 1)
9287  return;
9288 
9289  unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9290  bool IsStdAbs = IsStdFunction(FDecl, "abs");
9291  if (AbsKind == 0 && !IsStdAbs)
9292  return;
9293 
9294  QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9295  QualType ParamType = Call->getArg(0)->getType();
9296 
9297  // Unsigned types cannot be negative. Suggest removing the absolute value
9298  // function call.
9299  if (ArgType->isUnsignedIntegerType()) {
9300  const char *FunctionName =
9301  IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9302  Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9303  Diag(Call->getExprLoc(), diag::note_remove_abs)
9304  << FunctionName
9306  return;
9307  }
9308 
9309  // Taking the absolute value of a pointer is very suspicious, they probably
9310  // wanted to index into an array, dereference a pointer, call a function, etc.
9311  if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9312  unsigned DiagType = 0;
9313  if (ArgType->isFunctionType())
9314  DiagType = 1;
9315  else if (ArgType->isArrayType())
9316  DiagType = 2;
9317 
9318  Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9319  return;
9320  }
9321 
9322  // std::abs has overloads which prevent most of the absolute value problems
9323  // from occurring.
9324  if (IsStdAbs)
9325  return;
9326 
9327  AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9328  AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9329 
9330  // The argument and parameter are the same kind. Check if they are the right
9331  // size.
9332  if (ArgValueKind == ParamValueKind) {
9333  if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9334  return;
9335 
9336  unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9337  Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9338  << FDecl << ArgType << ParamType;
9339 
9340  if (NewAbsKind == 0)
9341  return;
9342 
9343  emitReplacement(*this, Call->getExprLoc(),
9344  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9345  return;
9346  }
9347 
9348  // ArgValueKind != ParamValueKind
9349  // The wrong type of absolute value function was used. Attempt to find the
9350  // proper one.
9351  unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9352  NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9353  if (NewAbsKind == 0)
9354  return;
9355 
9356  Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9357  << FDecl << ParamValueKind << ArgValueKind;
9358 
9359  emitReplacement(*this, Call->getExprLoc(),
9360  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9361 }
9362 
9363 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9364 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9365  const FunctionDecl *FDecl) {
9366  if (!Call || !FDecl) return;
9367 
9368  // Ignore template specializations and macros.
9369  if (inTemplateInstantiation()) return;
9370  if (Call->getExprLoc().isMacroID()) return;
9371 
9372  // Only care about the one template argument, two function parameter std::max
9373  if (Call->getNumArgs() != 2) return;
9374  if (!IsStdFunction(FDecl, "max")) return;
9375  const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9376  if (!ArgList) return;
9377  if (ArgList->size() != 1) return;
9378 
9379  // Check that template type argument is unsigned integer.
9380  const auto& TA = ArgList->get(0);
9381  if (TA.getKind() != TemplateArgument::Type) return;
9382  QualType ArgType = TA.getAsType();
9383  if (!ArgType->isUnsignedIntegerType()) return;
9384 
9385  // See if either argument is a literal zero.
9386  auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9387  const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9388  if (!MTE) return false;
9389  const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9390  if (!Num) return false;
9391  if (Num->getValue() != 0) return false;
9392  return true;
9393  };
9394 
9395  const Expr *FirstArg = Call->getArg(0);
9396  const Expr *SecondArg = Call->getArg(1);
9397  const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9398  const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9399 
9400  // Only warn when exactly one argument is zero.
9401  if (IsFirstArgZero == IsSecondArgZero) return;
9402 
9403  SourceRange FirstRange = FirstArg->getSourceRange();
9404  SourceRange SecondRange = SecondArg->getSourceRange();
9405 
9406  SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9407 
9408  Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9409  << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9410 
9411  // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9412  SourceRange RemovalRange;
9413  if (IsFirstArgZero) {
9414  RemovalRange = SourceRange(FirstRange.getBegin(),
9415  SecondRange.getBegin().getLocWithOffset(-1));
9416  } else {
9417  RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9418  SecondRange.getEnd());
9419  }
9420 
9421  Diag(Call->getExprLoc(), diag::note_remove_max_call)
9423  << FixItHint::CreateRemoval(RemovalRange);
9424 }
9425 
9426 //===--- CHECK: Standard memory functions ---------------------------------===//
9427 
9428 /// Takes the expression passed to the size_t parameter of functions
9429 /// such as memcmp, strncat, etc and warns if it's a comparison.
9430 ///
9431 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9432 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9433  IdentifierInfo *FnName,
9434  SourceLocation FnLoc,
9435  SourceLocation RParenLoc) {
9436  const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9437  if (!Size)
9438  return false;
9439 
9440  // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9441  if (!Size->isComparisonOp() && !Size->isLogicalOp())
9442  return false;
9443 
9444  SourceRange SizeRange = Size->getSourceRange();
9445  S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9446  << SizeRange << FnName;
9447  S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9448  << FnName
9450  S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9451  << FixItHint::CreateRemoval(RParenLoc);
9452  S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9453  << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9455  ")");
9456 
9457  return true;
9458 }
9459 
9460 /// Determine whether the given type is or contains a dynamic class type
9461 /// (e.g., whether it has a vtable).
9463  bool &IsContained) {
9464  // Look through array types while ignoring qualifiers.
9465  const Type *Ty = T->getBaseElementTypeUnsafe();
9466  IsContained = false;
9467 
9468  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9469  RD = RD ? RD->getDefinition() : nullptr;
9470  if (!RD || RD->isInvalidDecl())
9471  return nullptr;
9472 
9473  if (RD->isDynamicClass())
9474  return RD;
9475 
9476  // Check all the fields. If any bases were dynamic, the class is dynamic.
9477  // It's impossible for a class to transitively contain itself by value, so
9478  // infinite recursion is impossible.
9479  for (auto *FD : RD->fields()) {
9480  bool SubContained;
9481  if (const CXXRecordDecl *ContainedRD =
9482  getContainedDynamicClass(FD->getType(), SubContained)) {
9483  IsContained = true;
9484  return ContainedRD;
9485  }
9486  }
9487 
9488  return nullptr;
9489 }
9490 
9492  if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9493  if (Unary->getKind() == UETT_SizeOf)
9494  return Unary;
9495  return nullptr;
9496 }
9497 
9498 /// If E is a sizeof expression, returns its argument expression,
9499 /// otherwise returns NULL.
9500 static const Expr *getSizeOfExprArg(const Expr *E) {
9501  if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9502  if (!SizeOf->isArgumentType())
9503  return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9504  return nullptr;
9505 }
9506 
9507 /// If E is a sizeof expression, returns its argument type.
9508 static QualType getSizeOfArgType(const Expr *E) {
9509  if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9510  return SizeOf->getTypeOfArgument();
9511  return QualType();
9512 }
9513 
9514 namespace {
9515 
9516 struct SearchNonTrivialToInitializeField
9517  : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9518  using Super =
9520 
9521  SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9522 
9523  void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9524  SourceLocation SL) {
9525  if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9526  asDerived().visitArray(PDIK, AT, SL);
9527  return;
9528  }
9529 
9530  Super::visitWithKind(PDIK, FT, SL);
9531  }
9532 
9533  void visitARCStrong(QualType FT, SourceLocation SL) {
9534  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9535  }
9536  void visitARCWeak(QualType FT, SourceLocation SL) {
9537  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9538  }
9539  void visitStruct(QualType FT, SourceLocation SL) {
9540  for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9541  visit(FD->getType(), FD->getLocation());
9542  }
9543  void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9544  const ArrayType *AT, SourceLocation SL) {
9545  visit(getContext().getBaseElementType(AT), SL);
9546  }
9547  void visitTrivial(QualType FT, SourceLocation SL) {}
9548 
9549  static void diag(QualType RT, const Expr *E, Sema &S) {
9550  SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9551  }
9552 
9553  ASTContext &getContext() { return S.getASTContext(); }
9554 
9555  const Expr *E;
9556  Sema &S;
9557 };
9558 
9559 struct SearchNonTrivialToCopyField
9560  : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9562 
9563  SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9564 
9565  void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9566  SourceLocation SL) {
9567  if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9568  asDerived().visitArray(PCK, AT, SL);
9569  return;
9570  }
9571 
9572  Super::visitWithKind(PCK, FT, SL);
9573  }
9574 
9575  void visitARCStrong(QualType FT, SourceLocation SL) {
9576  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9577  }
9578  void visitARCWeak(QualType FT, SourceLocation SL) {
9579  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9580  }
9581  void visitStruct(QualType FT, SourceLocation SL) {
9582  for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9583  visit(FD->getType(), FD->getLocation());
9584  }
9585  void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9586  SourceLocation SL) {
9587  visit(getContext().getBaseElementType(AT), SL);
9588  }
9589  void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9590  SourceLocation SL) {}
9591  void visitTrivial(QualType FT, SourceLocation SL) {}
9592  void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9593 
9594  static void diag(QualType RT, const Expr *E, Sema &S) {
9595  SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9596  }
9597 
9598  ASTContext &getContext() { return S.getASTContext(); }
9599 
9600  const Expr *E;
9601  Sema &S;
9602 };
9603 
9604 }
9605 
9606 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9607 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9608  SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9609 
9610  if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9611  if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9612  return false;
9613 
9614  return doesExprLikelyComputeSize(BO->getLHS()) ||
9615  doesExprLikelyComputeSize(BO->getRHS());
9616  }
9617 
9618  return getAsSizeOfExpr(SizeofExpr) != nullptr;
9619 }
9620 
9621 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9622 ///
9623 /// \code
9624 /// #define MACRO 0
9625 /// foo(MACRO);
9626 /// foo(0);
9627 /// \endcode
9628 ///
9629 /// This should return true for the first call to foo, but not for the second
9630 /// (regardless of whether foo is a macro or function).
9632  SourceLocation CallLoc,
9633  SourceLocation ArgLoc) {
9634  if (!CallLoc.isMacroID())
9635  return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9636 
9637  return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9638  SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9639 }
9640 
9641 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9642 /// last two arguments transposed.
9643 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9644  if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9645  return;
9646 
9647  const Expr *SizeArg =
9648  Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9649 
9650  auto isLiteralZero = [](const Expr *E) {
9651  return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9652  };
9653 
9654  // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9655  SourceLocation CallLoc = Call->getRParenLoc();
9657  if (isLiteralZero(SizeArg) &&
9658  !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9659 
9660  SourceLocation DiagLoc = SizeArg->getExprLoc();
9661 
9662  // Some platforms #define bzero to __builtin_memset. See if this is the
9663  // case, and if so, emit a better diagnostic.
9664  if (BId == Builtin::BIbzero ||
9666  CallLoc, SM, S.getLangOpts()) == "bzero")) {
9667  S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9668  S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9669  } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9670  S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9671  S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9672  }
9673  return;
9674  }
9675 
9676  // If the second argument to a memset is a sizeof expression and the third
9677  // isn't, this is also likely an error. This should catch
9678  // 'memset(buf, sizeof(buf), 0xff)'.
9679  if (BId == Builtin::BImemset &&
9680  doesExprLikelyComputeSize(Call->getArg(1)) &&
9681  !doesExprLikelyComputeSize(Call->getArg(2))) {
9682  SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9683  S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9684  S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9685  return;
9686  }
9687 }
9688 
9689 /// Check for dangerous or invalid arguments to memset().
9690 ///
9691 /// This issues warnings on known problematic, dangerous or unspecified
9692 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9693 /// function calls.
9694 ///
9695 /// \param Call The call expression to diagnose.
9696 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9697  unsigned BId,
9698  IdentifierInfo *FnName) {
9699  assert(BId != 0);
9700 
9701  // It is possible to have a non-standard definition of memset. Validate
9702  // we have enough arguments, and if not, abort further checking.
9703  unsigned ExpectedNumArgs =
9704  (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9705  if (Call->getNumArgs() < ExpectedNumArgs)
9706  return;
9707 
9708  unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9709  BId == Builtin::BIstrndup ? 1 : 2);
9710  unsigned LenArg =
9711  (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9712  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9713 
9714  if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9715  Call->getBeginLoc(), Call->getRParenLoc()))
9716  return;
9717 
9718  // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9719  CheckMemaccessSize(*this, BId, Call);
9720 
9721  // We have special checking when the length is a sizeof expression.
9722  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9723  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9724  llvm::FoldingSetNodeID SizeOfArgID;
9725 
9726  // Although widely used, 'bzero' is not a standard function. Be more strict
9727  // with the argument types before allowing diagnostics and only allow the
9728  // form bzero(ptr, sizeof(...)).
9729  QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9730  if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9731  return;
9732 
9733  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9734  const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9735  SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9736 
9737  QualType DestTy = Dest->getType();
9738  QualType PointeeTy;
9739  if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9740  PointeeTy = DestPtrTy->getPointeeType();
9741 
9742  // Never warn about void type pointers. This can be used to suppress
9743  // false positives.
9744  if (PointeeTy->isVoidType())
9745  continue;
9746 
9747  // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9748  // actually comparing the expressions for equality. Because computing the
9749  // expression IDs can be expensive, we only do this if the diagnostic is
9750  // enabled.
9751  if (SizeOfArg &&
9752  !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9753  SizeOfArg->getExprLoc())) {
9754  // We only compute IDs for expressions if the warning is enabled, and
9755  // cache the sizeof arg's ID.
9756  if (SizeOfArgID == llvm::FoldingSetNodeID())
9757  SizeOfArg->Profile(SizeOfArgID, Context, true);
9758  llvm::FoldingSetNodeID DestID;
9759  Dest->Profile(DestID, Context, true);
9760  if (DestID == SizeOfArgID) {
9761  // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9762  // over sizeof(src) as well.
9763  unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9764  StringRef ReadableName = FnName->getName();
9765 
9766  if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9767  if (UnaryOp->getOpcode() == UO_AddrOf)
9768  ActionIdx = 1; // If its an address-of operator, just remove it.
9769  if (!PointeeTy->isIncompleteType() &&
9770  (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9771  ActionIdx = 2; // If the pointee's size is sizeof(char),
9772  // suggest an explicit length.
9773 
9774  // If the function is defined as a builtin macro, do not show macro
9775  // expansion.
9776  SourceLocation SL = SizeOfArg->getExprLoc();
9777  SourceRange DSR = Dest->getSourceRange();
9778  SourceRange SSR = SizeOfArg->getSourceRange();
9779  SourceManager &SM = getSourceManager();
9780 
9781  if (SM.isMacroArgExpansion(SL)) {
9782  ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9783  SL = SM.getSpellingLoc(SL);
9784  DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9785  SM.getSpellingLoc(DSR.getEnd()));
9786  SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9787  SM.getSpellingLoc(SSR.getEnd()));
9788  }
9789 
9790  DiagRuntimeBehavior(SL, SizeOfArg,
9791  PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9792  << ReadableName
9793  << PointeeTy
9794  << DestTy
9795  << DSR
9796  << SSR);
9797  DiagRuntimeBehavior(SL, SizeOfArg,
9798  PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9799  << ActionIdx
9800  << SSR);
9801 
9802  break;
9803  }
9804  }
9805 
9806  // Also check for cases where the sizeof argument is the exact same
9807  // type as the memory argument, and where it points to a user-defined
9808  // record type.
9809  if (SizeOfArgTy != QualType()) {
9810  if (PointeeTy->isRecordType() &&
9811  Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9812  DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9813  PDiag(diag::warn_sizeof_pointer_type_memaccess)
9814  << FnName << SizeOfArgTy << ArgIdx
9815  << PointeeTy << Dest->getSourceRange()
9816  << LenExpr->getSourceRange());
9817  break;
9818  }
9819  }
9820  } else if (DestTy->isArrayType()) {
9821  PointeeTy = DestTy;
9822  }
9823 
9824  if (PointeeTy == QualType())
9825  continue;
9826 
9827  // Always complain about dynamic classes.
9828  bool IsContained;
9829  if (const CXXRecordDecl *ContainedRD =
9830  getContainedDynamicClass(PointeeTy, IsContained)) {
9831 
9832  unsigned OperationType = 0;
9833  const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9834  // "overwritten" if we're warning about the destination for any call
9835  // but memcmp; otherwise a verb appropriate to the call.
9836  if (ArgIdx != 0 || IsCmp) {
9837  if (BId == Builtin::BImemcpy)
9838  OperationType = 1;
9839  else if(BId == Builtin::BImemmove)
9840  OperationType = 2;
9841  else if (IsCmp)
9842  OperationType = 3;
9843  }
9844 
9845  DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9846  PDiag(diag::warn_dyn_class_memaccess)
9847  << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9848  << IsContained << ContainedRD << OperationType
9849  << Call->getCallee()->getSourceRange());
9850  } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9851  BId != Builtin::BImemset)
9852  DiagRuntimeBehavior(
9853  Dest->getExprLoc(), Dest,
9854  PDiag(diag::warn_arc_object_memaccess)
9855  << ArgIdx << FnName << PointeeTy
9856  << Call->getCallee()->getSourceRange());
9857  else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9858  if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9859  RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9860  DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9861  PDiag(diag::warn_cstruct_memaccess)
9862  << ArgIdx << FnName << PointeeTy << 0);
9863  SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9864  } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9865  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9866  DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9867  PDiag(diag::warn_cstruct_memaccess)
9868  << ArgIdx << FnName << PointeeTy << 1);
9869  SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9870  } else {
9871  continue;
9872  }
9873  } else
9874  continue;
9875 
9876  DiagRuntimeBehavior(
9877  Dest->getExprLoc(), Dest,
9878  PDiag(diag::note_bad_memaccess_silence)
9879  << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9880  break;
9881  }
9882 }
9883 
9884 // A little helper routine: ignore addition and subtraction of integer literals.
9885 // This intentionally does not ignore all integer constant expressions because
9886 // we don't want to remove sizeof().
9887 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9888  Ex = Ex->IgnoreParenCasts();
9889 
9890  while (true) {
9891  const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9892  if (!BO || !BO->isAdditiveOp())
9893  break;
9894 
9895  const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9896  const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9897 
9898  if (isa<IntegerLiteral>(RHS))
9899  Ex = LHS;
9900  else if (isa<IntegerLiteral>(LHS))
9901  Ex = RHS;
9902  else
9903  break;
9904  }
9905 
9906  return Ex;
9907 }
9908 
9910  ASTContext &Context) {
9911  // Only handle constant-sized or VLAs, but not flexible members.
9912  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9913  // Only issue the FIXIT for arrays of size > 1.
9914  if (CAT->getSize().getSExtValue() <= 1)
9915  return false;
9916  } else if (!Ty->isVariableArrayType()) {
9917  return false;
9918  }
9919  return true;
9920 }
9921 
9922 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9923 // be the size of the source, instead of the destination.
9924 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9925  IdentifierInfo *FnName) {
9926 
9927  // Don't crash if the user has the wrong number of arguments
9928  unsigned NumArgs = Call->getNumArgs();
9929  if ((NumArgs != 3) && (NumArgs != 4))
9930  return;
9931 
9932  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9933  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9934  const Expr *CompareWithSrc = nullptr;
9935 
9936  if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9937  Call->getBeginLoc(), Call->getRParenLoc()))
9938  return;
9939 
9940  // Look for 'strlcpy(dst, x, sizeof(x))'
9941  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9942  CompareWithSrc = Ex;
9943  else {
9944  // Look for 'strlcpy(dst, x, strlen(x))'
9945  if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9946  if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9947  SizeCall->getNumArgs() == 1)
9948  CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9949  }
9950  }
9951 
9952  if (!CompareWithSrc)
9953  return;
9954 
9955  // Determine if the argument to sizeof/strlen is equal to the source
9956  // argument. In principle there's all kinds of things you could do
9957  // here, for instance creating an == expression and evaluating it with
9958  // EvaluateAsBooleanCondition, but this uses a more direct technique:
9959  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9960  if (!SrcArgDRE)
9961  return;
9962 
9963  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9964  if (!CompareWithSrcDRE ||
9965  SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9966  return;
9967 
9968  const Expr *OriginalSizeArg = Call->getArg(2);
9969  Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9970  << OriginalSizeArg->getSourceRange() << FnName;
9971 
9972  // Output a FIXIT hint if the destination is an array (rather than a
9973  // pointer to an array). This could be enhanced to handle some
9974  // pointers if we know the actual size, like if DstArg is 'array+2'
9975  // we could say 'sizeof(array)-2'.
9976  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9977  if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9978  return;
9979 
9980  SmallString<128> sizeString;
9981  llvm::raw_svector_ostream OS(sizeString);
9982  OS << "sizeof(";
9983  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9984  OS << ")";
9985 
9986  Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9987  << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9988  OS.str());
9989 }
9990 
9991 /// Check if two expressions refer to the same declaration.
9992 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9993  if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9994  if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9995  return D1->getDecl() == D2->getDecl();
9996  return false;
9997 }
9998 
9999 static const Expr *getStrlenExprArg(const Expr *E) {
10000  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10001  const FunctionDecl *FD = CE->getDirectCallee();
10002  if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10003  return nullptr;
10004  return CE->getArg(0)->IgnoreParenCasts();
10005  }
10006  return nullptr;
10007 }
10008 
10009 // Warn on anti-patterns as the 'size' argument to strncat.
10010 // The correct size argument should look like following:
10011 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10012 void Sema::CheckStrncatArguments(const CallExpr *CE,
10013  IdentifierInfo *FnName) {
10014  // Don't crash if the user has the wrong number of arguments.
10015  if (CE->getNumArgs() < 3)
10016  return;
10017  const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10018  const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10019  const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10020 
10021  if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10022  CE->getRParenLoc()))
10023  return;
10024 
10025  // Identify common expressions, which are wrongly used as the size argument
10026  // to strncat and may lead to buffer overflows.
10027  unsigned PatternType = 0;
10028  if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10029  // - sizeof(dst)
10030  if (referToTheSameDecl(SizeOfArg, DstArg))
10031  PatternType = 1;
10032  // - sizeof(src)
10033  else if (referToTheSameDecl(SizeOfArg, SrcArg))
10034  PatternType = 2;
10035  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10036  if (BE->getOpcode() == BO_Sub) {
10037  const Expr *L = BE->getLHS()->IgnoreParenCasts();
10038  const Expr *R = BE->getRHS()->IgnoreParenCasts();
10039  // - sizeof(dst) - strlen(dst)
10040  if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10042  PatternType = 1;
10043  // - sizeof(src) - (anything)
10044  else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10045  PatternType = 2;
10046  }
10047  }
10048 
10049  if (PatternType == 0)
10050  return;
10051 
10052  // Generate the diagnostic.
10053  SourceLocation SL = LenArg->getBeginLoc();
10054  SourceRange SR = LenArg->getSourceRange();
10055  SourceManager &SM = getSourceManager();
10056 
10057  // If the function is defined as a builtin macro, do not show macro expansion.
10058  if (SM.isMacroArgExpansion(SL)) {
10059  SL = SM.getSpellingLoc(SL);
10060  SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10061  SM.getSpellingLoc(SR.getEnd()));
10062  }
10063 
10064  // Check if the destination is an array (rather than a pointer to an array).
10065  QualType DstTy = DstArg->getType();
10066  bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10067  Context);
10068  if (!isKnownSizeArray) {
10069  if (PatternType == 1)
10070  Diag(SL, diag::warn_strncat_wrong_size) << SR;
10071  else
10072  Diag(SL, diag::warn_strncat_src_size) << SR;
10073  return;
10074  }
10075 
10076  if (PatternType == 1)
10077  Diag(SL, diag::warn_strncat_large_size) << SR;
10078  else
10079  Diag(SL, diag::warn_strncat_src_size) << SR;
10080 
10081  SmallString<128> sizeString;
10082  llvm::raw_svector_ostream OS(sizeString);
10083  OS << "sizeof(";
10084  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10085  OS << ") - ";
10086  OS << "strlen(";
10087  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10088  OS << ") - 1";
10089 
10090  Diag(SL, diag::note_strncat_wrong_size)
10091  << FixItHint::CreateReplacement(SR, OS.str());
10092 }
10093 
10094 void
10095 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10096  SourceLocation ReturnLoc,
10097  bool isObjCMethod,
10098  const AttrVec *Attrs,
10099  const FunctionDecl *FD) {
10100  // Check if the return value is null but should not be.
10101  if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10102  (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10103  CheckNonNullExpr(*this, RetValExp))
10104  Diag(ReturnLoc, diag::warn_null_ret)
10105  << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10106 
10107  // C++11 [basic.stc.dynamic.allocation]p4:
10108  // If an allocation function declared with a non-throwing
10109  // exception-specification fails to allocate storage, it shall return
10110  // a null pointer. Any other allocation function that fails to allocate
10111  // storage shall indicate failure only by throwing an exception [...]
10112  if (FD) {
10114  if (Op == OO_New || Op == OO_Array_New) {
10115  const FunctionProtoType *Proto
10116  = FD->getType()->castAs<FunctionProtoType>();
10117  if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10118  CheckNonNullExpr(*this, RetValExp))
10119  Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10120  << FD << getLangOpts().CPlusPlus11;
10121  }
10122  }
10123 }
10124 
10125 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10126 
10127 /// Check for comparisons of floating point operands using != and ==.
10128 /// Issue a warning if these are no self-comparisons, as they are not likely
10129 /// to do what the programmer intended.
10131  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10132  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10133 
10134  // Special case: check for x == x (which is OK).
10135  // Do not emit warnings for such cases.
10136  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10137  if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10138  if (DRL->getDecl() == DRR->getDecl())
10139  return;
10140 
10141  // Special case: check for comparisons against literals that can be exactly
10142  // represented by APFloat. In such cases, do not emit a warning. This
10143  // is a heuristic: often comparison against such literals are used to
10144  // detect if a value in a variable has not changed. This clearly can
10145  // lead to false negatives.
10146  if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10147  if (FLL->isExact())
10148  return;
10149  } else
10150  if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10151  if (FLR->isExact())
10152  return;
10153 
10154  // Check for comparisons with builtin types.
10155  if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10156  if (CL->getBuiltinCallee())
10157  return;
10158 
10159  if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10160  if (CR->getBuiltinCallee())
10161  return;
10162 
10163  // Emit the diagnostic.
10164  Diag(Loc, diag::warn_floatingpoint_eq)
10165  << LHS->getSourceRange() << RHS->getSourceRange();
10166 }
10167 
10168 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10169 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10170 
10171 namespace {
10172 
10173 /// Structure recording the 'active' range of an integer-valued
10174 /// expression.
10175 struct IntRange {
10176  /// The number of bits active in the int.
10177  unsigned Width;
10178 
10179  /// True if the int is known not to have negative values.
10180  bool NonNegative;
10181 
10182  IntRange(unsigned Width, bool NonNegative)
10183  : Width(Width), NonNegative(NonNegative) {}
10184 
10185  /// Returns the range of the bool type.
10186  static IntRange forBoolType() {
10187  return IntRange(1, true);
10188  }
10189 
10190  /// Returns the range of an opaque value of the given integral type.
10191  static IntRange forValueOfType(ASTContext &C, QualType T) {
10192  return forValueOfCanonicalType(C,
10194  }
10195 
10196  /// Returns the range of an opaque value of a canonical integral type.
10197  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10198  assert(T->isCanonicalUnqualified());
10199 
10200  if (const VectorType *VT = dyn_cast<VectorType>(T))
10201  T = VT->getElementType().getTypePtr();
10202  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10203  T = CT->getElementType().getTypePtr();
10204  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10205  T = AT->getValueType().getTypePtr();
10206 
10207  if (!C.getLangOpts().CPlusPlus) {
10208  // For enum types in C code, use the underlying datatype.
10209  if (const EnumType *ET = dyn_cast<EnumType>(T))
10210  T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10211  } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10212  // For enum types in C++, use the known bit width of the enumerators.
10213  EnumDecl *Enum = ET->getDecl();
10214  // In C++11, enums can have a fixed underlying type. Use this type to
10215  // compute the range.
10216  if (Enum->isFixed()) {
10217  return IntRange(C.getIntWidth(QualType(T, 0)),
10218  !ET->isSignedIntegerOrEnumerationType());
10219  }
10220 
10221  unsigned NumPositive = Enum->getNumPositiveBits();
10222  unsigned NumNegative = Enum->getNumNegativeBits();
10223 
10224  if (NumNegative == 0)
10225  return IntRange(NumPositive, true/*NonNegative*/);
10226  else
10227  return IntRange(std::max(NumPositive + 1, NumNegative),
10228  false/*NonNegative*/);
10229  }
10230 
10231  const BuiltinType *BT = cast<BuiltinType>(T);
10232  assert(BT->isInteger());
10233 
10234  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10235  }
10236 
10237  /// Returns the "target" range of a canonical integral type, i.e.
10238  /// the range of values expressible in the type.
10239  ///
10240  /// This matches forValueOfCanonicalType except that enums have the
10241  /// full range of their type, not the range of their enumerators.
10242  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10243  assert(T->isCanonicalUnqualified());
10244 
10245  if (const VectorType *VT = dyn_cast<VectorType>(T))
10246  T = VT->getElementType().getTypePtr();
10247  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10248  T = CT->getElementType().getTypePtr();
10249  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10250  T = AT->getValueType().getTypePtr();
10251  if (const EnumType *ET = dyn_cast<EnumType>(T))
10252  T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10253 
10254  const BuiltinType *BT = cast<BuiltinType>(T);
10255  assert(BT->isInteger());
10256 
10257  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10258  }
10259 
10260  /// Returns the supremum of two ranges: i.e. their conservative merge.
10261  static IntRange join(IntRange L, IntRange R) {
10262  return IntRange(std::max(L.Width, R.Width),
10263  L.NonNegative && R.NonNegative);
10264  }
10265 
10266  /// Returns the infinum of two ranges: i.e. their aggressive merge.
10267  static IntRange meet(IntRange L, IntRange R) {
10268  return IntRange(std::min(L.Width, R.Width),
10269  L.NonNegative || R.NonNegative);
10270  }
10271 };
10272 
10273 } // namespace
10274 
10275 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10276  unsigned MaxWidth) {
10277  if (value.isSigned() && value.isNegative())
10278  return IntRange(value.getMinSignedBits(), false);
10279 
10280  if (value.getBitWidth() > MaxWidth)
10281  value = value.trunc(MaxWidth);
10282 
10283  // isNonNegative() just checks the sign bit without considering
10284  // signedness.
10285  return IntRange(value.getActiveBits(), true);
10286 }
10287 
10288 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10289  unsigned MaxWidth) {
10290  if (result.isInt())
10291  return GetValueRange(C, result.getInt(), MaxWidth);
10292 
10293  if (result.isVector()) {
10294  IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10295  for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10296  IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10297  R = IntRange::join(R, El);
10298  }
10299  return R;
10300  }
10301 
10302  if (result.isComplexInt()) {
10303  IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10304  IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10305  return IntRange::join(R, I);
10306  }
10307 
10308  // This can happen with lossless casts to intptr_t of "based" lvalues.
10309  // Assume it might use arbitrary bits.
10310  // FIXME: The only reason we need to pass the type in here is to get
10311  // the sign right on this one case. It would be nice if APValue
10312  // preserved this.
10313  assert(result.isLValue() || result.isAddrLabelDiff());
10314  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10315 }
10316 
10317 static QualType GetExprType(const Expr *E) {
10318  QualType Ty = E->getType();
10319  if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10320  Ty = AtomicRHS->getValueType();
10321  return Ty;
10322 }
10323 
10324 /// Pseudo-evaluate the given integer expression, estimating the
10325 /// range of values it might take.
10326 ///
10327 /// \param MaxWidth - the width to which the value will be truncated
10328 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10329  bool InConstantContext) {
10330  E = E->IgnoreParens();
10331 
10332  // Try a full evaluation first.
10333  Expr::EvalResult result;
10334  if (E->EvaluateAsRValue(result, C, InConstantContext))
10335  return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10336 
10337  // I think we only want to look through implicit casts here; if the
10338  // user has an explicit widening cast, we should treat the value as
10339  // being of the new, wider type.
10340  if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10341  if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10342  return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10343 
10344  IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10345 
10346  bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10347  CE->getCastKind() == CK_BooleanToSignedIntegral;
10348 
10349  // Assume that non-integer casts can span the full range of the type.
10350  if (!isIntegerCast)
10351  return OutputTypeRange;
10352 
10353  IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10354  std::min(MaxWidth, OutputTypeRange.Width),
10355  InConstantContext);
10356 
10357  // Bail out if the subexpr's range is as wide as the cast type.
10358  if (SubRange.Width >= OutputTypeRange.Width)
10359  return OutputTypeRange;
10360 
10361  // Otherwise, we take the smaller width, and we're non-negative if
10362  // either the output type or the subexpr is.
10363  return IntRange(SubRange.Width,
10364  SubRange.NonNegative || OutputTypeRange.NonNegative);
10365  }
10366 
10367  if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10368  // If we can fold the condition, just take that operand.
10369  bool CondResult;
10370  if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10371  return GetExprRange(C,
10372  CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10373  MaxWidth, InConstantContext);
10374 
10375  // Otherwise, conservatively merge.
10376  IntRange L =
10377  GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10378  IntRange R =
10379  GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10380  return IntRange::join(L, R);
10381  }
10382 
10383  if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10384  switch (BO->getOpcode()) {
10385  case BO_Cmp:
10386  llvm_unreachable("builtin <=> should have class type");
10387 
10388  // Boolean-valued operations are single-bit and positive.
10389  case BO_LAnd:
10390  case BO_LOr:
10391  case BO_LT:
10392  case BO_GT:
10393  case BO_LE:
10394  case BO_GE:
10395  case BO_EQ:
10396  case BO_NE:
10397  return IntRange::forBoolType();
10398 
10399  // The type of the assignments is the type of the LHS, so the RHS
10400  // is not necessarily the same type.
10401  case BO_MulAssign:
10402  case BO_DivAssign:
10403  case BO_RemAssign:
10404  case BO_AddAssign:
10405  case BO_SubAssign:
10406  case BO_XorAssign:
10407  case BO_OrAssign:
10408  // TODO: bitfields?
10409  return IntRange::forValueOfType(C, GetExprType(E));
10410 
10411  // Simple assignments just pass through the RHS, which will have
10412  // been coerced to the LHS type.
10413  case BO_Assign:
10414  // TODO: bitfields?
10415  return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10416 
10417  // Operations with opaque sources are black-listed.
10418  case BO_PtrMemD:
10419  case BO_PtrMemI:
10420  return IntRange::forValueOfType(C, GetExprType(E));
10421 
10422  // Bitwise-and uses the *infinum* of the two source ranges.
10423  case BO_And:
10424  case BO_AndAssign:
10425  return IntRange::meet(
10426  GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10427  GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10428 
10429  // Left shift gets black-listed based on a judgement call.
10430  case BO_Shl:
10431  // ...except that we want to treat '1 << (blah)' as logically
10432  // positive. It's an important idiom.
10433  if (IntegerLiteral *I
10434  = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10435  if (I->getValue() == 1) {
10436  IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10437  return IntRange(R.Width, /*NonNegative*/ true);
10438  }
10439  }
10440  LLVM_FALLTHROUGH;
10441 
10442  case BO_ShlAssign:
10443  return IntRange::forValueOfType(C, GetExprType(E));
10444 
10445  // Right shift by a constant can narrow its left argument.
10446  case BO_Shr:
10447  case BO_ShrAssign: {
10448  IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10449 
10450  // If the shift amount is a positive constant, drop the width by
10451  // that much.
10452  llvm::APSInt shift;
10453  if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10454  shift.isNonNegative()) {
10455  unsigned zext = shift.getZExtValue();
10456  if (zext >= L.Width)
10457  L.Width = (L.NonNegative ? 0 : 1);
10458  else
10459  L.Width -= zext;
10460  }
10461 
10462  return L;
10463  }
10464 
10465  // Comma acts as its right operand.
10466  case BO_Comma:
10467  return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10468 
10469  // Black-list pointer subtractions.
10470  case BO_Sub:
10471  if (BO->getLHS()->getType()->isPointerType())
10472  return IntRange::forValueOfType(C, GetExprType(E));
10473  break;
10474 
10475  // The width of a division result is mostly determined by the size
10476  // of the LHS.
10477  case BO_Div: {
10478  // Don't 'pre-truncate' the operands.
10479  unsigned opWidth = C.getIntWidth(GetExprType(E));
10480  IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10481 
10482  // If the divisor is constant, use that.
10483  llvm::APSInt divisor;
10484  if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10485  unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10486  if (log2 >= L.Width)
10487  L.Width = (L.NonNegative ? 0 : 1);
10488  else
10489  L.Width = std::min(L.Width - log2, MaxWidth);
10490  return L;
10491  }
10492 
10493  // Otherwise, just use the LHS's width.
10494  IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10495  return IntRange(L.Width, L.NonNegative && R.NonNegative);
10496  }
10497 
10498  // The result of a remainder can't be larger than the result of
10499  // either side.
10500  case BO_Rem: {
10501  // Don't 'pre-truncate' the operands.
10502  unsigned opWidth = C.getIntWidth(GetExprType(E));
10503  IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10504  IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10505 
10506  IntRange meet = IntRange::meet(L, R);
10507  meet.Width = std::min(meet.Width, MaxWidth);
10508  return meet;
10509  }
10510 
10511  // The default behavior is okay for these.
10512  case BO_Mul:
10513  case BO_Add:
10514  case BO_Xor:
10515  case BO_Or:
10516  break;
10517  }
10518 
10519  // The default case is to treat the operation as if it were closed
10520  // on the narrowest type that encompasses both operands.
10521  IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10522  IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10523  return IntRange::join(L, R);
10524  }
10525 
10526  if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10527  switch (UO->getOpcode()) {
10528  // Boolean-valued operations are white-listed.
10529  case UO_LNot:
10530  return IntRange::forBoolType();
10531 
10532  // Operations with opaque sources are black-listed.
10533  case UO_Deref:
10534  case UO_AddrOf: // should be impossible
10535  return IntRange::forValueOfType(C, GetExprType(E));
10536 
10537  default:
10538  return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10539  }
10540  }
10541 
10542  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10543  return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10544 
10545  if (const auto *BitField = E->getSourceBitField())
10546  return IntRange(BitField->getBitWidthValue(C),
10547  BitField->getType()->isUnsignedIntegerOrEnumerationType());
10548 
10549  return IntRange::forValueOfType(C, GetExprType(E));
10550 }
10551 
10552 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10553  bool InConstantContext) {
10554  return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10555 }
10556 
10557 /// Checks whether the given value, which currently has the given
10558 /// source semantics, has the same value when coerced through the
10559 /// target semantics.
10560 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10561  const llvm::fltSemantics &Src,
10562  const llvm::fltSemantics &Tgt) {
10563  llvm::APFloat truncated = value;
10564 
10565  bool ignored;
10566  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10567  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10568 
10569  return truncated.bitwiseIsEqual(value);
10570 }
10571 
10572 /// Checks whether the given value, which currently has the given
10573 /// source semantics, has the same value when coerced through the
10574 /// target semantics.
10575 ///
10576 /// The value might be a vector of floats (or a complex number).
10577 static bool IsSameFloatAfterCast(const APValue &value,
10578  const llvm::fltSemantics &Src,
10579  const llvm::fltSemantics &Tgt) {
10580  if (value.isFloat())
10581  return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10582 
10583  if (value.isVector()) {
10584  for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10585  if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10586  return false;
10587  return true;
10588  }
10589 
10590  assert(value.isComplexFloat());
10591  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10592  IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10593 }
10594 
10595 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10596  bool IsListInit = false);
10597 
10598 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10599  // Suppress cases where we are comparing against an enum constant.
10600  if (const DeclRefExpr *DR =
10601  dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10602  if (isa<EnumConstantDecl>(DR->getDecl()))
10603  return true;
10604 
10605  // Suppress cases where the value is expanded from a macro, unless that macro
10606  // is how a language represents a boolean literal. This is the case in both C
10607  // and Objective-C.
10608  SourceLocation BeginLoc = E->getBeginLoc();
10609  if (BeginLoc.isMacroID()) {
10610  StringRef MacroName = Lexer::getImmediateMacroName(
10611  BeginLoc, S.getSourceManager(), S.getLangOpts());
10612  return MacroName != "YES" && MacroName != "NO" &&
10613  MacroName != "true" && MacroName != "false";
10614  }
10615 
10616  return false;
10617 }
10618 
10620  return E->getType()->isIntegerType() &&
10621  (!E->getType()->isSignedIntegerType() ||
10623 }
10624 
10625 namespace {
10626 /// The promoted range of values of a type. In general this has the
10627 /// following structure:
10628 ///
10629 /// |-----------| . . . |-----------|
10630 /// ^ ^ ^ ^
10631 /// Min HoleMin HoleMax Max
10632 ///
10633 /// ... where there is only a hole if a signed type is promoted to unsigned
10634 /// (in which case Min and Max are the smallest and largest representable
10635 /// values).
10636 struct PromotedRange {
10637  // Min, or HoleMax if there is a hole.
10638  llvm::APSInt PromotedMin;
10639  // Max, or HoleMin if there is a hole.
10640  llvm::APSInt PromotedMax;
10641 
10642  PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10643  if (R.Width == 0)
10644  PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10645  else if (R.Width >= BitWidth && !Unsigned) {
10646  // Promotion made the type *narrower*. This happens when promoting
10647  // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10648  // Treat all values of 'signed int' as being in range for now.
10649  PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10650  PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10651  } else {
10652  PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10653  .extOrTrunc(BitWidth);
10654  PromotedMin.setIsUnsigned(Unsigned);
10655 
10656  PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10657  .extOrTrunc(BitWidth);
10658  PromotedMax.setIsUnsigned(Unsigned);
10659  }
10660  }
10661 
10662  // Determine whether this range is contiguous (has no hole).
10663  bool isContiguous() const { return PromotedMin <= PromotedMax; }
10664 
10665  // Where a constant value is within the range.
10666  enum ComparisonResult {
10667  LT = 0x1,
10668  LE = 0x2,
10669  GT = 0x4,
10670  GE = 0x8,
10671  EQ = 0x10,
10672  NE = 0x20,
10673  InRangeFlag = 0x40,
10674 
10675  Less = LE | LT | NE,
10676  Min = LE | InRangeFlag,
10677  InRange = InRangeFlag,
10678  Max = GE | InRangeFlag,
10679  Greater = GE | GT | NE,
10680 
10681  OnlyValue = LE | GE | EQ | InRangeFlag,
10682  InHole = NE
10683  };
10684 
10685  ComparisonResult compare(const llvm::APSInt &Value) const {
10686  assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10687  Value.isUnsigned() == PromotedMin.isUnsigned());
10688  if (!isContiguous()) {
10689  assert(Value.isUnsigned() && "discontiguous range for signed compare");
10690  if (Value.isMinValue()) return Min;
10691  if (Value.isMaxValue()) return Max;
10692  if (Value >= PromotedMin) return InRange;
10693  if (Value <= PromotedMax) return InRange;
10694  return InHole;
10695  }
10696 
10697  switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10698  case -1: return Less;
10699  case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10700  case 1:
10701  switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10702  case -1: return InRange;
10703  case 0: return Max;
10704  case 1: return Greater;
10705  }
10706  }
10707 
10708  llvm_unreachable("impossible compare result");
10709  }
10710 
10712  constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10713  if (Op == BO_Cmp) {
10714  ComparisonResult LTFlag = LT, GTFlag = GT;
10715  if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10716 
10717  if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10718  if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10719  if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10720  return llvm::None;
10721  }
10722 
10723  ComparisonResult TrueFlag, FalseFlag;
10724  if (Op == BO_EQ) {
10725  TrueFlag = EQ;
10726  FalseFlag = NE;
10727  } else if (Op == BO_NE) {
10728  TrueFlag = NE;
10729  FalseFlag = EQ;
10730  } else {
10731  if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10732  TrueFlag = LT;
10733  FalseFlag = GE;
10734  } else {
10735  TrueFlag = GT;
10736  FalseFlag = LE;
10737  }
10738  if (Op == BO_GE || Op == BO_LE)
10739  std::swap(TrueFlag, FalseFlag);
10740  }
10741  if (R & TrueFlag)
10742  return StringRef("true");
10743  if (R & FalseFlag)
10744  return StringRef("false");
10745  return llvm::None;
10746  }
10747 };
10748 }
10749 
10750 static bool HasEnumType(Expr *E) {
10751  // Strip off implicit integral promotions.
10752  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10753  if (ICE->getCastKind() != CK_IntegralCast &&
10754  ICE->getCastKind() != CK_NoOp)
10755  break;
10756  E = ICE->getSubExpr();
10757  }
10758 
10759  return E->getType()->isEnumeralType();
10760 }
10761 
10762 static int classifyConstantValue(Expr *Constant) {
10763  // The values of this enumeration are used in the diagnostics
10764  // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10765  enum ConstantValueKind {
10766  Miscellaneous = 0,
10767  LiteralTrue,
10768  LiteralFalse
10769  };
10770  if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10771  return BL->getValue() ? ConstantValueKind::LiteralTrue
10772  : ConstantValueKind::LiteralFalse;
10773  return ConstantValueKind::Miscellaneous;
10774 }
10775 
10777  Expr *Constant, Expr *Other,
10778  const llvm::APSInt &Value,
10779  bool RhsConstant) {
10780  if (S.inTemplateInstantiation())
10781  return false;
10782 
10783  Expr *OriginalOther = Other;
10784 
10785  Constant = Constant->IgnoreParenImpCasts();
10786  Other = Other->IgnoreParenImpCasts();
10787 
10788  // Suppress warnings on tautological comparisons between values of the same
10789  // enumeration type. There are only two ways we could warn on this:
10790  // - If the constant is outside the range of representable values of
10791  // the enumeration. In such a case, we should warn about the cast
10792  // to enumeration type, not about the comparison.
10793  // - If the constant is the maximum / minimum in-range value. For an
10794  // enumeratin type, such comparisons can be meaningful and useful.
10795  if (Constant->getType()->isEnumeralType() &&
10796  S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10797  return false;
10798 
10799  // TODO: Investigate using GetExprRange() to get tighter bounds
10800  // on the bit ranges.
10801  QualType OtherT = Other->getType();
10802  if (const auto *AT = OtherT->getAs<AtomicType>())
10803  OtherT = AT->getValueType();
10804  IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10805 
10806  // Special case for ObjC BOOL on targets where its a typedef for a signed char
10807  // (Namely, macOS).
10808  bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10809  S.NSAPIObj->isObjCBOOLType(OtherT) &&
10810  OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10811 
10812  // Whether we're treating Other as being a bool because of the form of
10813  // expression despite it having another type (typically 'int' in C).
10814  bool OtherIsBooleanDespiteType =
10815  !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10816  if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10817  OtherRange = IntRange::forBoolType();
10818 
10819  // Determine the promoted range of the other type and see if a comparison of
10820  // the constant against that range is tautological.
10821  PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10822  Value.isUnsigned());
10823  auto Cmp = OtherPromotedRange.compare(Value);
10824  auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10825  if (!Result)
10826  return false;
10827 
10828  // Suppress the diagnostic for an in-range comparison if the constant comes
10829  // from a macro or enumerator. We don't want to diagnose
10830  //
10831  // some_long_value <= INT_MAX
10832  //
10833  // when sizeof(int) == sizeof(long).
10834  bool InRange = Cmp & PromotedRange::InRangeFlag;
10835  if (InRange && IsEnumConstOrFromMacro(S, Constant))
10836  return false;
10837 
10838  // If this is a comparison to an enum constant, include that
10839  // constant in the diagnostic.
10840  const EnumConstantDecl *ED = nullptr;
10841  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10842  ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10843 
10844  // Should be enough for uint128 (39 decimal digits)
10845  SmallString<64> PrettySourceValue;
10846  llvm::raw_svector_ostream OS(PrettySourceValue);
10847  if (ED) {
10848  OS << '\'' << *ED << "' (" << Value << ")";
10849  } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10850  Constant->IgnoreParenImpCasts())) {
10851  OS << (BL->getValue() ? "YES" : "NO");
10852  } else {
10853  OS << Value;
10854  }
10855 
10856  if (IsObjCSignedCharBool) {
10858  S.PDiag(diag::warn_tautological_compare_objc_bool)
10859  << OS.str() << *Result);
10860  return true;
10861  }
10862 
10863  // FIXME: We use a somewhat different formatting for the in-range cases and
10864  // cases involving boolean values for historical reasons. We should pick a
10865  // consistent way of presenting these diagnostics.
10866  if (!InRange || Other->isKnownToHaveBooleanValue()) {
10867 
10869  E->getOperatorLoc(), E,
10870  S.PDiag(!InRange ? diag::warn_out_of_range_compare
10871  : diag::warn_tautological_bool_compare)
10872  << OS.str() << classifyConstantValue(Constant) << OtherT
10873  << OtherIsBooleanDespiteType << *Result
10874  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10875  } else {
10876  unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10877  ? (HasEnumType(OriginalOther)
10878  ? diag::warn_unsigned_enum_always_true_comparison
10879  : diag::warn_unsigned_always_true_comparison)
10880  : diag::warn_tautological_constant_compare;
10881 
10882  S.Diag(E->getOperatorLoc(), Diag)
10883  << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10884  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10885  }
10886 
10887  return true;
10888 }
10889 
10890 /// Analyze the operands of the given comparison. Implements the
10891 /// fallback case from AnalyzeComparison.
10895 }
10896 
10897 /// Implements -Wsign-compare.
10898 ///
10899 /// \param E the binary operator to check for warnings
10901  // The type the comparison is being performed in.
10902  QualType T = E->getLHS()->getType();
10903 
10904  // Only analyze comparison operators where both sides have been converted to
10905  // the same type.
10906  if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10907  return AnalyzeImpConvsInComparison(S, E);
10908 
10909  // Don't analyze value-dependent comparisons directly.
10910  if (E->isValueDependent())
10911  return AnalyzeImpConvsInComparison(S, E);
10912 
10913  Expr *LHS = E->getLHS();
10914  Expr *RHS = E->getRHS();
10915 
10916  if (T->isIntegralType(S.Context)) {
10917  llvm::APSInt RHSValue;
10918  llvm::APSInt LHSValue;
10919 
10920  bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10921  bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10922 
10923  // We don't care about expressions whose result is a constant.
10924  if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10925  return AnalyzeImpConvsInComparison(S, E);
10926 
10927  // We only care about expressions where just one side is literal
10928  if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10929  // Is the constant on the RHS or LHS?
10930  const bool RhsConstant = IsRHSIntegralLiteral;
10931  Expr *Const = RhsConstant ? RHS : LHS;
10932  Expr *Other = RhsConstant ? LHS : RHS;
10933  const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10934 
10935  // Check whether an integer constant comparison results in a value
10936  // of 'true' or 'false'.
10937  if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10938  return AnalyzeImpConvsInComparison(S, E);
10939  }
10940  }
10941 
10943  // We don't do anything special if this isn't an unsigned integral
10944  // comparison: we're only interested in integral comparisons, and
10945  // signed comparisons only happen in cases we don't care to warn about.
10946  return AnalyzeImpConvsInComparison(S, E);
10947  }
10948 
10949  LHS = LHS->IgnoreParenImpCasts();
10950  RHS = RHS->IgnoreParenImpCasts();
10951 
10952  if (!S.getLangOpts().CPlusPlus) {
10953  // Avoid warning about comparison of integers with different signs when
10954  // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10955  // the type of `E`.
10956  if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10957  LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10958  if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10959  RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10960  }
10961 
10962  // Check to see if one of the (unmodified) operands is of different
10963  // signedness.
10964  Expr *signedOperand, *unsignedOperand;
10965  if (LHS->getType()->hasSignedIntegerRepresentation()) {
10966  assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10967  "unsigned comparison between two signed integer expressions?");
10968  signedOperand = LHS;
10969  unsignedOperand = RHS;
10970  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10971  signedOperand = RHS;
10972  unsignedOperand = LHS;
10973  } else {
10974  return AnalyzeImpConvsInComparison(S, E);
10975  }
10976 
10977  // Otherwise, calculate the effective range of the signed operand.
10978  IntRange signedRange =
10979  GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10980 
10981  // Go ahead and analyze implicit conversions in the operands. Note
10982  // that we skip the implicit conversions on both sides.
10985 
10986  // If the signed range is non-negative, -Wsign-compare won't fire.
10987  if (signedRange.NonNegative)
10988  return;
10989 
10990  // For (in)equality comparisons, if the unsigned operand is a
10991  // constant which cannot collide with a overflowed signed operand,
10992  // then reinterpreting the signed operand as unsigned will not
10993  // change the result of the comparison.
10994  if (E->isEqualityOp()) {
10995  unsigned comparisonWidth = S.Context.getIntWidth(T);
10996  IntRange unsignedRange =
10997  GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10998 
10999  // We should never be unable to prove that the unsigned operand is
11000  // non-negative.
11001  assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11002 
11003  if (unsignedRange.Width < comparisonWidth)
11004  return;
11005  }
11006 
11008  S.PDiag(diag::warn_mixed_sign_comparison)
11009  << LHS->getType() << RHS->getType()
11010  << LHS->getSourceRange() << RHS->getSourceRange());
11011 }
11012 
11013 /// Analyzes an attempt to assign the given value to a bitfield.
11014 ///
11015 /// Returns true if there was something fishy about the attempt.
11016 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11017  SourceLocation InitLoc) {
11018  assert(Bitfield->isBitField());
11019  if (Bitfield->isInvalidDecl())
11020  return false;
11021 
11022  // White-list bool bitfields.
11023  QualType BitfieldType = Bitfield->getType();
11024  if (BitfieldType->isBooleanType())
11025  return false;
11026 
11027  if (BitfieldType->isEnumeralType()) {
11028  EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11029  // If the underlying enum type was not explicitly specified as an unsigned
11030  // type and the enum contain only positive values, MSVC++ will cause an
11031  // inconsistency by storing this as a signed type.
11032  if (S.getLangOpts().CPlusPlus11 &&
11033  !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11034  BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11035  BitfieldEnumDecl->getNumNegativeBits() == 0) {
11036  S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11037  << BitfieldEnumDecl->getNameAsString();
11038  }
11039  }
11040 
11041  if (Bitfield->getType()->isBooleanType())
11042  return false;
11043 
11044  // Ignore value- or type-dependent expressions.
11045  if (Bitfield->getBitWidth()->isValueDependent() ||
11046  Bitfield->getBitWidth()->isTypeDependent() ||
11047  Init->isValueDependent() ||
11048  Init->isTypeDependent())
11049  return false;
11050 
11051  Expr *OriginalInit = Init->IgnoreParenImpCasts();
11052  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11053 
11054  Expr::EvalResult Result;
11055  if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11057  // The RHS is not constant. If the RHS has an enum type, make sure the
11058  // bitfield is wide enough to hold all the values of the enum without
11059  // truncation.
11060  if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11061  EnumDecl *ED = EnumTy->getDecl();
11062  bool SignedBitfield = BitfieldType->isSignedIntegerType();
11063 
11064  // Enum types are implicitly signed on Windows, so check if there are any
11065  // negative enumerators to see if the enum was intended to be signed or
11066  // not.
11067  bool SignedEnum = ED->getNumNegativeBits() > 0;
11068 
11069  // Check for surprising sign changes when assigning enum values to a
11070  // bitfield of different signedness. If the bitfield is signed and we
11071  // have exactly the right number of bits to store this unsigned enum,
11072  // suggest changing the enum to an unsigned type. This typically happens
11073  // on Windows where unfixed enums always use an underlying type of 'int'.
11074  unsigned DiagID = 0;
11075  if (SignedEnum && !SignedBitfield) {
11076  DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11077  } else if (SignedBitfield && !SignedEnum &&
11078  ED->getNumPositiveBits() == FieldWidth) {
11079  DiagID = diag::warn_signed_bitfield_enum_conversion;
11080  }
11081 
11082  if (DiagID) {
11083  S.Diag(InitLoc, DiagID) << Bitfield << ED;
11084  TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11085  SourceRange TypeRange =
11086  TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11087  S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11088  << SignedEnum << TypeRange;
11089  }
11090 
11091  // Compute the required bitwidth. If the enum has negative values, we need
11092  // one more bit than the normal number of positive bits to represent the
11093  // sign bit.
11094  unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11095  ED->getNumNegativeBits())
11096  : ED->getNumPositiveBits();
11097 
11098  // Check the bitwidth.
11099  if (BitsNeeded > FieldWidth) {
11100  Expr *WidthExpr = Bitfield->getBitWidth();
11101  S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11102  << Bitfield << ED;
11103  S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11104  << BitsNeeded << ED << WidthExpr->getSourceRange();
11105  }
11106  }
11107 
11108  return false;
11109  }
11110 
11111  llvm::APSInt Value = Result.Val.getInt();
11112 
11113  unsigned OriginalWidth = Value.getBitWidth();
11114 
11115  if (!Value.isSigned() || Value.isNegative())
11116  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11117  if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11118  OriginalWidth = Value.getMinSignedBits();
11119 
11120  if (OriginalWidth <= FieldWidth)
11121  return false;
11122 
11123  // Compute the value which the bitfield will contain.
11124  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11125  TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11126 
11127  // Check whether the stored value is equal to the original value.
11128  TruncatedValue = TruncatedValue.extend(OriginalWidth);
11129  if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11130  return false;
11131 
11132  // Special-case bitfields of width 1: booleans are naturally 0/1, and
11133  // therefore don't strictly fit into a signed bitfield of width 1.
11134  if (FieldWidth == 1 && Value == 1)
11135  return false;
11136 
11137  std::string PrettyValue = Value.toString(10);
11138  std::string PrettyTrunc = TruncatedValue.toString(10);
11139 
11140  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11141  << PrettyValue << PrettyTrunc << OriginalInit->getType()
11142  << Init->getSourceRange();
11143 
11144  return true;
11145 }
11146 
11147 /// Analyze the given simple or compound assignment for warning-worthy
11148 /// operations.
11150  // Just recurse on the LHS.
11152 
11153  // We want to recurse on the RHS as normal unless we're assigning to
11154  // a bitfield.
11155  if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11156  if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11157  E->getOperatorLoc())) {
11158  // Recurse, ignoring any implicit conversions on the RHS.
11160  E->getOperatorLoc());
11161  }
11162  }
11163 
11165 
11166  // Diagnose implicitly sequentially-consistent atomic assignment.
11167  if (E->getLHS()->getType()->isAtomicType())
11168  S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11169 }
11170 
11171 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11172 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11173  SourceLocation CContext, unsigned diag,
11174  bool pruneControlFlow = false) {
11175  if (pruneControlFlow) {
11176  S.DiagRuntimeBehavior(E->getExprLoc(), E,
11177  S.PDiag(diag)
11178  << SourceType << T << E->getSourceRange()
11179  << SourceRange(CContext));
11180  return;
11181  }
11182  S.Diag(E->getExprLoc(), diag)
11183  << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11184 }
11185 
11186 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11187 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11188  SourceLocation CContext,
11189  unsigned diag, bool pruneControlFlow = false) {
11190  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11191 }
11192 
11193 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11194  return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11195  S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11196 }
11197 
11199  Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11200  Expr *Ignored = SourceExpr->IgnoreImplicit();
11201  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11202  Ignored = OVE->getSourceExpr();
11203  bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11204  isa<BinaryOperator>(Ignored) ||
11205  isa<CXXOperatorCallExpr>(Ignored);
11206  SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11207  if (NeedsParens)
11208  Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11209  << FixItHint::CreateInsertion(EndLoc, ")");
11210  Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11211 }
11212 
11213 /// Diagnose an implicit cast from a floating point value to an integer value.
11215  SourceLocation CContext) {
11216  const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11217  const bool PruneWarnings = S.inTemplateInstantiation();
11218 
11219  Expr *InnerE = E->IgnoreParenImpCasts();
11220  // We also want to warn on, e.g., "int i = -1.234"
11221  if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11222  if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11223  InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11224 
11225  const bool IsLiteral =
11226  isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11227 
11228  llvm::APFloat Value(0.0);
11229  bool IsConstant =
11231  if (!IsConstant) {
11232  if (isObjCSignedCharBool(S, T)) {
11234  S, E,
11235  S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11236  << E->getType());
11237  }
11238 
11239  return DiagnoseImpCast(S, E, T, CContext,
11240  diag::warn_impcast_float_integer, PruneWarnings);
11241  }
11242 
11243  bool isExact = false;
11244 
11245  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11247  llvm::APFloat::opStatus Result = Value.convertToInteger(
11248  IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11249 
11250  // FIXME: Force the precision of the source value down so we don't print
11251  // digits which are usually useless (we don't really care here if we
11252  // truncate a digit by accident in edge cases). Ideally, APFloat::toString
11253  // would automatically print the shortest representation, but it's a bit
11254  // tricky to implement.
11255  SmallString<16> PrettySourceValue;
11256  unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11257  precision = (precision * 59 + 195) / 196;
11258  Value.toString(PrettySourceValue, precision);
11259 
11260  if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11262  S, E,
11263  S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11264  << PrettySourceValue);
11265  }
11266 
11267  if (Result == llvm::APFloat::opOK && isExact) {
11268  if (IsLiteral) return;
11269  return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11270  PruneWarnings);
11271  }
11272 
11273  // Conversion of a floating-point value to a non-bool integer where the
11274  // integral part cannot be represented by the integer type is undefined.
11275  if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11276  return DiagnoseImpCast(
11277  S, E, T, CContext,
11278  IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11279  : diag::warn_impcast_float_to_integer_out_of_range,
11280  PruneWarnings);
11281 
11282  unsigned DiagID = 0;
11283  if (IsLiteral) {
11284  // Warn on floating point literal to integer.
11285  DiagID = diag::warn_impcast_literal_float_to_integer;
11286  } else if (IntegerValue == 0) {
11287  if (Value.isZero()) { // Skip -0.0 to 0 conversion.
11288  return DiagnoseImpCast(S, E, T, CContext,
11289  diag::warn_impcast_float_integer, PruneWarnings);
11290  }
11291  // Warn on non-zero to zero conversion.
11292  DiagID = diag::warn_impcast_float_to_integer_zero;
11293  } else {
11294  if (IntegerValue.isUnsigned()) {
11295  if (!IntegerValue.isMaxValue()) {
11296  return DiagnoseImpCast(S, E, T, CContext,
11297  diag::warn_impcast_float_integer, PruneWarnings);
11298  }
11299  } else { // IntegerValue.isSigned()
11300  if (!IntegerValue.isMaxSignedValue() &&
11301  !IntegerValue.isMinSignedValue()) {
11302  return DiagnoseImpCast(S, E, T, CContext,
11303  diag::warn_impcast_float_integer, PruneWarnings);
11304  }
11305  }
11306  // Warn on evaluatable floating point expression to integer conversion.
11307  DiagID = diag::warn_impcast_float_to_integer;
11308  }
11309 
11310  SmallString<16> PrettyTargetValue;
11311  if (IsBool)
11312  PrettyTargetValue = Value.isZero() ? "false" : "true";
11313  else
11314  IntegerValue.toString(PrettyTargetValue);
11315 
11316  if (PruneWarnings) {
11317  S.DiagRuntimeBehavior(E->getExprLoc(), E,
11318  S.PDiag(DiagID)
11319  << E->getType() << T.getUnqualifiedType()
11320  << PrettySourceValue << PrettyTargetValue
11321  << E->getSourceRange() << SourceRange(CContext));
11322  } else {
11323  S.Diag(E->getExprLoc(), DiagID)
11324  << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11325  << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11326  }
11327 }
11328 
11329 /// Analyze the given compound assignment for the possible losing of
11330 /// floating-point precision.
11332  assert(isa<CompoundAssignOperator>(E) &&
11333  "Must be compound assignment operation");
11334  // Recurse on the LHS and RHS in here
11337 
11338  if (E->getLHS()->getType()->isAtomicType())
11339  S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11340 
11341  // Now check the outermost expression
11342  const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11343  const auto *RBT = cast<CompoundAssignOperator>(E)
11344  ->getComputationResultType()
11345  ->getAs<BuiltinType>();
11346 
11347  // The below checks assume source is floating point.
11348  if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11349 
11350  // If source is floating point but target is an integer.
11351  if (ResultBT->isInteger())
11352  return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11353  E->getExprLoc(), diag::warn_impcast_float_integer);
11354 
11355  if (!ResultBT->isFloatingPoint())
11356  return;
11357 
11358  // If both source and target are floating points, warn about losing precision.
11360  QualType(ResultBT, 0), QualType(RBT, 0));
11361  if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11362  // warn about dropping FP rank.
11363  DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11364  diag::warn_impcast_float_result_precision);
11365 }
11366 
11367 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11368  IntRange Range) {
11369  if (!Range.Width) return "0";
11370 
11371  llvm::APSInt ValueInRange = Value;
11372  ValueInRange.setIsSigned(!Range.NonNegative);
11373  ValueInRange = ValueInRange.trunc(Range.Width);
11374  return ValueInRange.toString(10);
11375 }
11376 
11377 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11378  if (!isa<ImplicitCastExpr>(Ex))
11379  return false;
11380 
11381  Expr *InnerE = Ex->IgnoreParenImpCasts();
11382  const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11383  const Type *Source =
11384  S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11385  if (Target->isDependentType())
11386  return false;
11387 
11388  const BuiltinType *FloatCandidateBT =
11389  dyn_cast<BuiltinType>(ToBool ? Source : Target);
11390  const Type *BoolCandidateType = ToBool ? Target : Source;
11391 
11392  return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11393  FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11394 }
11395 
11397  SourceLocation CC) {
11398  unsigned NumArgs = TheCall->getNumArgs();
11399  for (unsigned i = 0; i < NumArgs; ++i) {
11400  Expr *CurrA = TheCall->getArg(i);
11401  if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11402  continue;
11403 
11404  bool IsSwapped = ((i > 0) &&
11405  IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11406  IsSwapped |= ((i < (NumArgs - 1)) &&
11407  IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11408  if (IsSwapped) {
11409  // Warn on this floating-point to bool conversion.
11411  CurrA->getType(), CC,
11412  diag::warn_impcast_floating_point_to_bool);
11413  }
11414  }
11415 }
11416 
11418  SourceLocation CC) {
11419  if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11420  E->getExprLoc()))
11421  return;
11422 
11423  // Don't warn on functions which have return type nullptr_t.
11424  if (isa<CallExpr>(E))
11425  return;
11426 
11427  // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11428  const Expr::NullPointerConstantKind NullKind =
11430  if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11431  return;
11432 
11433  // Return if target type is a safe conversion.
11434  if (T->isAnyPointerType() || T->isBlockPointerType() ||
11435  T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11436  return;
11437 
11438  SourceLocation Loc = E->getSourceRange().getBegin();
11439 
11440  // Venture through the macro stacks to get to the source of macro arguments.
11441  // The new location is a better location than the complete location that was
11442  // passed in.
11443  Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11444  CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11445 
11446  // __null is usually wrapped in a macro. Go up a macro if that is the case.
11447  if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11448  StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11449  Loc, S.SourceMgr, S.getLangOpts());
11450  if (MacroName == "NULL")
11452  }
11453 
11454  // Only warn if the null and context location are in the same macro expansion.
11455  if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11456  return;
11457 
11458  S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11459  << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11461  S.getFixItZeroLiteralForType(T, Loc));
11462 }
11463 
11464 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11465  ObjCArrayLiteral *ArrayLiteral);
11466 
11467 static void
11469  ObjCDictionaryLiteral *DictionaryLiteral);
11470 
11471 /// Check a single element within a collection literal against the
11472 /// target element type.
11474  QualType TargetElementType,
11475  Expr *Element,
11476  unsigned ElementKind) {
11477  // Skip a bitcast to 'id' or qualified 'id'.
11478  if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11479  if (ICE->getCastKind() == CK_BitCast &&
11480  ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11481  Element = ICE->getSubExpr();
11482  }
11483 
11484  QualType ElementType = Element->getType();
11485  ExprResult ElementResult(Element);
11486  if (ElementType->getAs<ObjCObjectPointerType>() &&
11487  S.CheckSingleAssignmentConstraints(TargetElementType,
11488  ElementResult,
11489  false, false)
11490  != Sema::Compatible) {
11491  S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11492  << ElementType << ElementKind << TargetElementType
11493  << Element->getSourceRange();
11494  }
11495 
11496  if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11497  checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11498  else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11499  checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11500 }
11501 
11502 /// Check an Objective-C array literal being converted to the given
11503 /// target type.
11504 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11505  ObjCArrayLiteral *ArrayLiteral) {
11506  if (!S.NSArrayDecl)
11507  return;
11508 
11509  const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11510  if (!TargetObjCPtr)
11511  return;
11512 
11513  if (TargetObjCPtr->isUnspecialized() ||
11514  TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11515  != S.NSArrayDecl->getCanonicalDecl())
11516  return;
11517 
11518  auto TypeArgs = TargetObjCPtr->getTypeArgs();
11519  if (TypeArgs.size() != 1)
11520  return;
11521 
11522  QualType TargetElementType = TypeArgs[0];
11523  for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11524  checkObjCCollectionLiteralElement(S, TargetElementType,
11525  ArrayLiteral->getElement(I),
11526  0);
11527  }
11528 }
11529 
11530 /// Check an Objective-C dictionary literal being converted to the given
11531 /// target type.
11532 static void
11534  ObjCDictionaryLiteral *DictionaryLiteral) {
11535  if (!S.NSDictionaryDecl)
11536  return;
11537 
11538  const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11539  if (!TargetObjCPtr)
11540  return;
11541 
11542  if (TargetObjCPtr->isUnspecialized() ||
11543  TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11545  return;
11546 
11547  auto TypeArgs = TargetObjCPtr->getTypeArgs();
11548  if (TypeArgs.size() != 2)
11549  return;
11550 
11551  QualType TargetKeyType = TypeArgs[0];
11552  QualType TargetObjectType = TypeArgs[1];
11553  for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11554  auto Element = DictionaryLiteral->getKeyValueElement(I);
11555  checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11556  checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11557  }
11558 }
11559 
11560 // Helper function to filter out cases for constant width constant conversion.
11561 // Don't warn on char array initialization or for non-decimal values.
11563  SourceLocation CC) {
11564  // If initializing from a constant, and the constant starts with '0',
11565  // then it is a binary, octal, or hexadecimal. Allow these constants
11566  // to fill all the bits, even if there is a sign change.
11567  if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11568  const char FirstLiteralCharacter =
11569  S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11570  if (FirstLiteralCharacter == '0')
11571  return false;
11572  }
11573 
11574  // If the CC location points to a '{', and the type is char, then assume
11575  // assume it is an array initialization.
11576  if (CC.isValid() && T->isCharType()) {
11577  const char FirstContextCharacter =
11579  if (FirstContextCharacter == '{')
11580  return false;
11581  }
11582 
11583  return true;
11584 }
11585 
11587  const auto *IL = dyn_cast<IntegerLiteral>(E);
11588  if (!IL) {
11589  if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11590  if (UO->getOpcode() == UO_Minus)
11591  return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11592  }
11593  }
11594 
11595  return IL;
11596 }
11597 
11598 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11599  E = E->IgnoreParenImpCasts();
11600  SourceLocation ExprLoc = E->getExprLoc();
11601 
11602  if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11603  BinaryOperator::Opcode Opc = BO->getOpcode();
11604  Expr::EvalResult Result;
11605  // Do not diagnose unsigned shifts.
11606  if (Opc == BO_Shl) {
11607  const auto *LHS = getIntegerLiteral(BO->getLHS());
11608  const auto *RHS = getIntegerLiteral(BO->getRHS());
11609  if (LHS && LHS->getValue() == 0)
11610  S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11611  else if (!E->isValueDependent() && LHS && RHS &&
11612  RHS->getValue().isNonNegative() &&
11614  S.Diag(ExprLoc, diag::warn_left_shift_always)
11615  << (Result.Val.getInt() != 0);
11616  else if (E->getType()->isSignedIntegerType())
11617  S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11618  }
11619  }
11620 
11621  if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11622  const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11623  const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11624  if (!LHS || !RHS)
11625  return;
11626  if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11627  (RHS->getValue() == 0 || RHS->getValue() == 1))
11628  // Do not diagnose common idioms.
11629  return;
11630  if (LHS->getValue() != 0 && RHS->getValue() != 0)
11631  S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11632  }
11633 }
11634 
11636  SourceLocation CC,
11637  bool *ICContext = nullptr,
11638  bool IsListInit = false) {
11639  if (E->isTypeDependent() || E->isValueDependent()) return;
11640 
11641  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11642  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11643  if (Source == Target) return;
11644  if (Target->isDependentType()) return;
11645 
11646  // If the conversion context location is invalid don't complain. We also
11647  // don't want to emit a warning if the issue occurs from the expansion of
11648  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11649  // delay this check as long as possible. Once we detect we are in that
11650  // scenario, we just return.
11651  if (CC.isInvalid())
11652  return;
11653 
11654  if (Source->isAtomicType())
11655  S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11656 
11657  // Diagnose implicit casts to bool.
11658  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11659  if (isa<StringLiteral>(E))
11660  // Warn on string literal to bool. Checks for string literals in logical
11661  // and expressions, for instance, assert(0 && "error here"), are
11662  // prevented by a check in AnalyzeImplicitConversions().
11663  return DiagnoseImpCast(S, E, T, CC,
11664  diag::warn_impcast_string_literal_to_bool);
11665  if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11666  isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11667  // This covers the literal expressions that evaluate to Objective-C
11668  // objects.
11669  return DiagnoseImpCast(S, E, T, CC,
11670  diag::warn_impcast_objective_c_literal_to_bool);
11671  }
11672  if (Source->isPointerType() || Source->canDecayToPointerType()) {
11673  // Warn on pointer to bool conversion that is always true.
11674  S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11675  SourceRange(CC));
11676  }
11677  }
11678 
11679  // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11680  // is a typedef for signed char (macOS), then that constant value has to be 1
11681  // or 0.
11682  if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11683  Expr::EvalResult Result;
11684  if (E->EvaluateAsInt(Result, S.getASTContext(),
11686  if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11688  S, E,
11689  S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11690  << Result.Val.getInt().toString(10));
11691  }
11692  return;
11693  }
11694  }
11695 
11696  // Check implicit casts from Objective-C collection literals to specialized
11697  // collection types, e.g., NSArray<NSString *> *.
11698  if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11699  checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11700  else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11701  checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11702 
11703  // Strip vector types.
11704  if (isa<VectorType>(Source)) {
11705  if (!isa<VectorType>(Target)) {
11706  if (S.SourceMgr.isInSystemMacro(CC))
11707  return;
11708  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11709  }
11710 
11711  // If the vector cast is cast between two vectors of the same size, it is
11712  // a bitcast, not a conversion.
11713  if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11714  return;
11715 
11716  Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11717  Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11718  }
11719  if (auto VecTy = dyn_cast<VectorType>(Target))
11720  Target = VecTy->getElementType().getTypePtr();
11721 
11722  // Strip complex types.
11723  if (isa<ComplexType>(Source)) {
11724  if (!isa<ComplexType>(Target)) {
11725  if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11726  return;
11727 
11728  return DiagnoseImpCast(S, E, T, CC,
11729  S.getLangOpts().CPlusPlus
11730  ? diag::err_impcast_complex_scalar
11731  : diag::warn_impcast_complex_scalar);
11732  }
11733 
11734  Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11735  Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11736  }
11737 
11738  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11739  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11740 
11741  // If the source is floating point...
11742  if (SourceBT && SourceBT->isFloatingPoint()) {
11743  // ...and the target is floating point...
11744  if (TargetBT && TargetBT->isFloatingPoint()) {
11745  // ...then warn if we're dropping FP rank.
11746 
11748  QualType(SourceBT, 0), QualType(TargetBT, 0));
11749  if (Order > 0) {
11750  // Don't warn about float constants that are precisely
11751  // representable in the target type.
11752  Expr::EvalResult result;
11753  if (E->EvaluateAsRValue(result, S.Context)) {
11754  // Value might be a float, a float vector, or a float complex.
11755  if (IsSameFloatAfterCast(result.Val,
11756  S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11757  S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11758  return;
11759  }
11760 
11761  if (S.SourceMgr.isInSystemMacro(CC))
11762  return;
11763 
11764  DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11765  }
11766  // ... or possibly if we're increasing rank, too
11767  else if (Order < 0) {
11768  if (S.SourceMgr.isInSystemMacro(CC))
11769  return;
11770 
11771  DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11772  }
11773  return;
11774  }
11775 
11776  // If the target is integral, always warn.
11777  if (TargetBT && TargetBT->isInteger()) {
11778  if (S.SourceMgr.isInSystemMacro(CC))
11779  return;
11780 
11781  DiagnoseFloatingImpCast(S, E, T, CC);
11782  }
11783 
11784  // Detect the case where a call result is converted from floating-point to
11785  // to bool, and the final argument to the call is converted from bool, to
11786  // discover this typo:
11787  //
11788  // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
11789  //
11790  // FIXME: This is an incredibly special case; is there some more general
11791  // way to detect this class of misplaced-parentheses bug?
11792  if (Target->isBooleanType() && isa<CallExpr>(E)) {
11793  // Check last argument of function call to see if it is an
11794  // implicit cast from a type matching the type the result
11795  // is being cast to.
11796  CallExpr *CEx = cast<CallExpr>(E);
11797  if (unsigned NumArgs = CEx->getNumArgs()) {
11798  Expr *LastA = CEx->getArg(NumArgs - 1);
11799  Expr *InnerE = LastA->IgnoreParenImpCasts();
11800  if (isa<ImplicitCastExpr>(LastA) &&
11801  InnerE->getType()->isBooleanType()) {
11802  // Warn on this floating-point to bool conversion
11803  DiagnoseImpCast(S, E, T, CC,
11804  diag::warn_impcast_floating_point_to_bool);
11805  }
11806  }
11807  }
11808  return;
11809  }
11810 
11811  // Valid casts involving fixed point types should be accounted for here.
11812  if (Source->isFixedPointType()) {
11813  if (Target->isUnsaturatedFixedPointType()) {
11814  Expr::EvalResult Result;
11816  S.isConstantEvaluated())) {
11817  APFixedPoint Value = Result.Val.getFixedPoint();
11818  APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11819  APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11820  if (Value > MaxVal || Value < MinVal) {
11821  S.DiagRuntimeBehavior(E->getExprLoc(), E,
11822  S.PDiag(diag::warn_impcast_fixed_point_range)
11823  << Value.toString() << T
11824  << E->getSourceRange()
11825  << clang::SourceRange(CC));
11826  return;
11827  }
11828  }
11829  } else if (Target->isIntegerType()) {
11830  Expr::EvalResult Result;
11831  if (!S.isConstantEvaluated() &&
11832  E->EvaluateAsFixedPoint(Result, S.Context,
11834  APFixedPoint FXResult = Result.Val.getFixedPoint();
11835 
11836  bool Overflowed;
11837  llvm::APSInt IntResult = FXResult.convertToInt(
11838  S.Context.getIntWidth(T),
11839  Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11840 
11841  if (Overflowed) {
11842  S.DiagRuntimeBehavior(E->getExprLoc(), E,
11843  S.PDiag(diag::warn_impcast_fixed_point_range)
11844  << FXResult.toString() << T
11845  << E->getSourceRange()
11846  << clang::SourceRange(CC));
11847  return;
11848  }
11849  }
11850  }
11851  } else if (Target->isUnsaturatedFixedPointType()) {
11852  if (Source->isIntegerType()) {
11853  Expr::EvalResult Result;
11854  if (!S.isConstantEvaluated() &&
11856  llvm::APSInt Value = Result.Val.getInt();
11857 
11858  bool Overflowed;
11860  Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11861 
11862  if (Overflowed) {
11863  S.DiagRuntimeBehavior(E->getExprLoc(), E,
11864  S.PDiag(diag::warn_impcast_fixed_point_range)
11865  << Value.toString(/*Radix=*/10) << T
11866  << E->getSourceRange()
11867  << clang::SourceRange(CC));
11868  return;
11869  }
11870  }
11871  }
11872  }
11873 
11874  // If we are casting an integer type to a floating point type without
11875  // initialization-list syntax, we might lose accuracy if the floating
11876  // point type has a narrower significand than the integer type.
11877  if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11878  TargetBT->isFloatingType() && !IsListInit) {
11879  // Determine the number of precision bits in the source integer type.
11880  IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11881  unsigned int SourcePrecision = SourceRange.Width;
11882 
11883  // Determine the number of precision bits in the
11884  // target floating point type.
11885  unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11886  S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11887 
11888  if (SourcePrecision > 0 && TargetPrecision > 0 &&
11889  SourcePrecision > TargetPrecision) {
11890 
11891  llvm::APSInt SourceInt;
11892  if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11893  // If the source integer is a constant, convert it to the target
11894  // floating point type. Issue a warning if the value changes
11895  // during the whole conversion.
11896  llvm::APFloat TargetFloatValue(
11897  S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11898  llvm::APFloat::opStatus ConversionStatus =
11899  TargetFloatValue.convertFromAPInt(
11900  SourceInt, SourceBT->isSignedInteger(),
11901  llvm::APFloat::rmNearestTiesToEven);
11902 
11903  if (ConversionStatus != llvm::APFloat::opOK) {
11904  std::string PrettySourceValue = SourceInt.toString(10);
11905  SmallString<32> PrettyTargetValue;
11906  TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11907 
11909  E->getExprLoc(), E,
11910  S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11911  << PrettySourceValue << PrettyTargetValue << E->getType() << T
11912  << E->getSourceRange() << clang::SourceRange(CC));
11913  }
11914  } else {
11915  // Otherwise, the implicit conversion may lose precision.
11916  DiagnoseImpCast(S, E, T, CC,
11917  diag::warn_impcast_integer_float_precision);
11918  }
11919  }
11920  }
11921 
11922  DiagnoseNullConversion(S, E, T, CC);
11923 
11924  S.DiscardMisalignedMemberAddress(Target, E);
11925 
11926  if (Target->isBooleanType())
11928 
11929  if (!Source->isIntegerType() || !Target->isIntegerType())
11930  return;
11931 
11932  // TODO: remove this early return once the false positives for constant->bool
11933  // in templates, macros, etc, are reduced or removed.
11934  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11935  return;
11936 
11937  if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11938  !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11940  S, E,
11941  S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11942  << E->getType());
11943  }
11944 
11945  IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11946  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11947 
11948  if (SourceRange.Width > TargetRange.Width) {
11949  // If the source is a constant, use a default-on diagnostic.
11950  // TODO: this should happen for bitfield stores, too.
11951  Expr::EvalResult Result;
11953  S.isConstantEvaluated())) {
11954  llvm::APSInt Value(32);
11955  Value = Result.Val.getInt();
11956 
11957  if (S.SourceMgr.isInSystemMacro(CC))
11958  return;
11959 
11960  std::string PrettySourceValue = Value.toString(10);
11961  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11962 
11964  E->getExprLoc(), E,
11965  S.PDiag(diag::warn_impcast_integer_precision_constant)
11966  << PrettySourceValue << PrettyTargetValue << E->getType() << T
11967  << E->getSourceRange() << clang::SourceRange(CC));
11968  return;
11969  }
11970 
11971  // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11972  if (S.SourceMgr.isInSystemMacro(CC))
11973  return;
11974 
11975  if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11976  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11977  /* pruneControlFlow */ true);
11978  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11979  }
11980 
11981  if (TargetRange.Width > SourceRange.Width) {
11982  if (auto *UO = dyn_cast<UnaryOperator>(E))
11983  if (UO->getOpcode() == UO_Minus)
11984  if (Source->isUnsignedIntegerType()) {
11985  if (Target->isUnsignedIntegerType())
11986  return DiagnoseImpCast(S, E, T, CC,
11987  diag::warn_impcast_high_order_zero_bits);
11988  if (Target->isSignedIntegerType())
11989  return DiagnoseImpCast(S, E, T, CC,
11990  diag::warn_impcast_nonnegative_result);
11991  }
11992  }
11993 
11994  if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11995  SourceRange.NonNegative && Source->isSignedIntegerType()) {
11996  // Warn when doing a signed to signed conversion, warn if the positive
11997  // source value is exactly the width of the target type, which will
11998  // cause a negative value to be stored.
11999 
12000  Expr::EvalResult Result;
12001  if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12002  !S.SourceMgr.isInSystemMacro(CC)) {
12003  llvm::APSInt Value = Result.Val.getInt();
12004  if (isSameWidthConstantConversion(S, E, T, CC)) {
12005  std::string PrettySourceValue = Value.toString(10);
12006  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12007 
12009  E->getExprLoc(), E,
12010  S.PDiag(diag::warn_impcast_integer_precision_constant)
12011  << PrettySourceValue << PrettyTargetValue << E->getType() << T
12012  << E->getSourceRange() << clang::SourceRange(CC));
12013  return;
12014  }
12015  }
12016 
12017  // Fall through for non-constants to give a sign conversion warning.
12018  }
12019 
12020  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
12021  (!TargetRange.NonNegative && SourceRange.NonNegative &&
12022  SourceRange.Width == TargetRange.Width)) {
12023  if (S.SourceMgr.isInSystemMacro(CC))
12024  return;
12025 
12026  unsigned DiagID = diag::warn_impcast_integer_sign;
12027 
12028  // Traditionally, gcc has warned about this under -Wsign-compare.
12029  // We also want to warn about it in -Wconversion.
12030  // So if -Wconversion is off, use a completely identical diagnostic
12031  // in the sign-compare group.
12032  // The conditional-checking code will
12033  if (ICContext) {
12034  DiagID = diag::warn_impcast_integer_sign_conditional;
12035  *ICContext = true;
12036  }
12037 
12038  return DiagnoseImpCast(S, E, T, CC, DiagID);
12039  }
12040 
12041  // Diagnose conversions between different enumeration types.
12042  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12043  // type, to give us better diagnostics.
12044  QualType SourceType = E->getType();
12045  if (!S.getLangOpts().CPlusPlus) {
12046  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12047  if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12048  EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12049  SourceType = S.Context.getTypeDeclType(Enum);
12050  Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12051  }
12052  }
12053 
12054  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12055  if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12056  if (SourceEnum->getDecl()->hasNameForLinkage() &&
12057  TargetEnum->getDecl()->hasNameForLinkage() &&
12058  SourceEnum != TargetEnum) {
12059  if (S.SourceMgr.isInSystemMacro(CC))
12060  return;
12061 
12062  return DiagnoseImpCast(S, E, SourceType, T, CC,
12063  diag::warn_impcast_different_enum_types);
12064  }
12065 }
12066 
12068  SourceLocation CC, QualType T);
12069 
12071  SourceLocation CC, bool &ICContext) {
12072  E = E->IgnoreParenImpCasts();
12073 
12074  if (isa<ConditionalOperator>(E))
12075  return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
12076 
12077  AnalyzeImplicitConversions(S, E, CC);
12078  if (E->getType() != T)
12079  return CheckImplicitConversion(S, E, T, CC, &ICContext);
12080 }
12081 
12083  SourceLocation CC, QualType T) {
12085 
12086  bool Suspicious = false;
12087  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
12088  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12089 
12090  if (T->isBooleanType())
12092 
12093  // If -Wconversion would have warned about either of the candidates
12094  // for a signedness conversion to the context type...
12095  if (!Suspicious) return;
12096 
12097  // ...but it's currently ignored...
12098  if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12099  return;
12100 
12101  // ...then check whether it would have warned about either of the
12102  // candidates for a signedness conversion to the condition type.
12103  if (E->getType() == T) return;
12104 
12105  Suspicious = false;
12107  E->getType(), CC, &Suspicious);
12108  if (!Suspicious)
12110  E->getType(), CC, &Suspicious);
12111 }
12112 
12113 /// Check conversion of given expression to boolean.
12114 /// Input argument E is a logical expression.
12116  if (S.getLangOpts().Bool)
12117  return;
12118  if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12119  return;
12121 }
12122 
12123 /// AnalyzeImplicitConversions - Find and report any interesting
12124 /// implicit conversions in the given expression. There are a couple
12125 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12127  bool IsListInit/*= false*/) {
12128  QualType T = OrigE->getType();
12129  Expr *E = OrigE->IgnoreParenImpCasts();
12130 
12131  // Propagate whether we are in a C++ list initialization expression.
12132  // If so, we do not issue warnings for implicit int-float conversion
12133  // precision loss, because C++11 narrowing already handles it.
12134  IsListInit =
12135  IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12136 
12137  if (E->isTypeDependent() || E->isValueDependent())
12138  return;
12139 
12140  if (const auto *UO = dyn_cast<UnaryOperator>(E))
12141  if (UO->getOpcode() == UO_Not &&
12142  UO->getSubExpr()->isKnownToHaveBooleanValue())
12143  S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12144  << OrigE->getSourceRange() << T->isBooleanType()
12145  << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12146 
12147  // For conditional operators, we analyze the arguments as if they
12148  // were being fed directly into the output.
12149  if (isa<ConditionalOperator>(E)) {
12150  ConditionalOperator *CO = cast<ConditionalOperator>(E);
12151  CheckConditionalOperator(S, CO, CC, T);
12152  return;
12153  }
12154 
12155  // Check implicit argument conversions for function calls.
12156  if (CallExpr *Call = dyn_cast<CallExpr>(E))
12157  CheckImplicitArgumentConversions(S, Call, CC);
12158 
12159  // Go ahead and check any implicit conversions we might have skipped.
12160  // The non-canonical typecheck is just an optimization;
12161  // CheckImplicitConversion will filter out dead implicit conversions.
12162  if (E->getType() != T)
12163  CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
12164 
12165  // Now continue drilling into this expression.
12166 
12167  if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12168  // The bound subexpressions in a PseudoObjectExpr are not reachable
12169  // as transitive children.
12170  // FIXME: Use a more uniform representation for this.
12171  for (auto *SE : POE->semantics())
12172  if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12173  AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
12174  }
12175 
12176  // Skip past explicit casts.
12177  if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12178  E = CE->getSubExpr()->IgnoreParenImpCasts();
12179  if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12180  S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12181  return AnalyzeImplicitConversions(S, E, CC, IsListInit);
12182  }
12183 
12184  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12185  // Do a somewhat different check with comparison operators.
12186  if (BO->isComparisonOp())
12187  return AnalyzeComparison(S, BO);
12188 
12189  // And with simple assignments.
12190  if (BO->getOpcode() == BO_Assign)
12191  return AnalyzeAssignment(S, BO);
12192  // And with compound assignments.
12193  if (BO->isAssignmentOp())
12194  return AnalyzeCompoundAssignment(S, BO);
12195  }
12196 
12197  // These break the otherwise-useful invariant below. Fortunately,
12198  // we don't really need to recurse into them, because any internal
12199  // expressions should have been analyzed already when they were
12200  // built into statements.
12201  if (isa<StmtExpr>(E)) return;
12202 
12203  // Don't descend into unevaluated contexts.
12204  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12205 
12206  // Now just recurse over the expression's children.
12207  CC = E->getExprLoc();
12208  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12209  bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12210  for (Stmt *SubStmt : E->children()) {
12211  Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12212  if (!ChildExpr)
12213  continue;
12214 
12215  if (IsLogicalAndOperator &&
12216  isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12217  // Ignore checking string literals that are in logical and operators.
12218  // This is a common pattern for asserts.
12219  continue;
12220  AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
12221  }
12222 
12223  if (BO && BO->isLogicalOp()) {
12224  Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12225  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12226  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12227 
12228  SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12229  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12230  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12231  }
12232 
12233  if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12234  if (U->getOpcode() == UO_LNot) {
12235  ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12236  } else if (U->getOpcode() != UO_AddrOf) {
12237  if (U->getSubExpr()->getType()->isAtomicType())
12238  S.Diag(U->getSubExpr()->getBeginLoc(),
12239  diag::warn_atomic_implicit_seq_cst);
12240  }
12241  }
12242 }
12243 
12244 /// Diagnose integer type and any valid implicit conversion to it.
12245 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12246  // Taking into account implicit conversions,
12247  // allow any integer.
12248  if (!E->getType()->isIntegerType()) {
12249  S.Diag(E->getBeginLoc(),
12250  diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12251  return true;
12252  }
12253  // Potentially emit standard warnings for implicit conversions if enabled
12254  // using -Wconversion.
12255  CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12256  return false;
12257 }
12258 
12259 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12260 // Returns true when emitting a warning about taking the address of a reference.
12261 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12262  const PartialDiagnostic &PD) {
12263  E = E->IgnoreParenImpCasts();
12264 
12265  const FunctionDecl *FD = nullptr;
12266 
12267  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12268  if (!DRE->getDecl()->getType()->isReferenceType())
12269  return false;
12270  } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12271  if (!M->getMemberDecl()->getType()->isReferenceType())
12272  return false;
12273  } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12274  if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12275  return false;
12276  FD = Call->getDirectCallee();
12277  } else {
12278  return false;
12279  }
12280 
12281  SemaRef.Diag(E->getExprLoc(), PD);
12282 
12283  // If possible, point to location of function.
12284  if (FD) {
12285  SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12286  }
12287 
12288  return true;
12289 }
12290 
12291 // Returns true if the SourceLocation is expanded from any macro body.
12292 // Returns false if the SourceLocation is invalid, is from not in a macro
12293 // expansion, or is from expanded from a top-level macro argument.
12295  if (Loc.isInvalid())
12296  return false;
12297 
12298  while (Loc.isMacroID()) {
12299  if (SM.isMacroBodyExpansion(Loc))
12300  return true;
12301  Loc = SM.getImmediateMacroCallerLoc(Loc);
12302  }
12303 
12304  return false;
12305 }
12306 
12307 /// Diagnose pointers that are always non-null.
12308 /// \param E the expression containing the pointer
12309 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12310 /// compared to a null pointer
12311 /// \param IsEqual True when the comparison is equal to a null pointer
12312 /// \param Range Extra SourceRange to highlight in the diagnostic
12315  bool IsEqual, SourceRange Range) {
12316  if (!E)
12317  return;
12318 
12319  // Don't warn inside macros.
12320  if (E->getExprLoc().isMacroID()) {
12321  const SourceManager &SM = getSourceManager();
12322  if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12323  IsInAnyMacroBody(SM, Range.getBegin()))
12324  return;
12325  }
12326  E = E->IgnoreImpCasts();
12327 
12328  const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12329 
12330  if (isa<CXXThisExpr>(E)) {
12331  unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12332  : diag::warn_this_bool_conversion;
12333  Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12334  return;
12335  }
12336 
12337  bool IsAddressOf = false;
12338 
12339  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12340  if (UO->getOpcode() != UO_AddrOf)
12341  return;
12342  IsAddressOf = true;
12343  E = UO->getSubExpr();
12344  }
12345 
12346  if (IsAddressOf) {
12347  unsigned DiagID = IsCompare
12348  ? diag::warn_address_of_reference_null_compare
12349  : diag::warn_address_of_reference_bool_conversion;
12350  PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12351  << IsEqual;
12352  if (CheckForReference(*this, E, PD)) {
12353  return;
12354  }
12355  }
12356 
12357  auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12358  bool IsParam = isa<NonNullAttr>(NonnullAttr);
12359  std::string Str;
12360  llvm::raw_string_ostream S(Str);
12361  E->printPretty(S, nullptr, getPrintingPolicy());
12362  unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12363  : diag::warn_cast_nonnull_to_bool;
12364  Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12365  << E->getSourceRange() << Range << IsEqual;
12366  Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12367  };
12368 
12369  // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12370  if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12371  if (auto *Callee = Call->getDirectCallee()) {
12372  if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12373  ComplainAboutNonnullParamOrCall(A);
12374  return;
12375  }
12376  }
12377  }
12378 
12379  // Expect to find a single Decl. Skip anything more complicated.
12380  ValueDecl *D = nullptr;
12381  if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12382  D = R->getDecl();
12383  } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12384  D = M->getMemberDecl();
12385  }
12386 
12387  // Weak Decls can be null.
12388  if (!D || D->isWeak())
12389  return;
12390 
12391  // Check for parameter decl with nonnull attribute
12392  if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12393  if (getCurFunction() &&
12394  !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12395  if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12396  ComplainAboutNonnullParamOrCall(A);
12397  return;
12398  }
12399 
12400  if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12401  // Skip function template not specialized yet.
12403  return;
12404  auto ParamIter = llvm::find(FD->parameters(), PV);
12405  assert(ParamIter != FD->param_end());
12406  unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12407 
12408  for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12409  if (!NonNull->args_size()) {
12410  ComplainAboutNonnullParamOrCall(NonNull);
12411  return;
12412  }
12413 
12414  for (const ParamIdx &ArgNo : NonNull->args()) {
12415  if (ArgNo.getASTIndex() == ParamNo) {
12416  ComplainAboutNonnullParamOrCall(NonNull);
12417  return;
12418  }
12419  }
12420  }
12421  }
12422  }
12423  }
12424 
12425  QualType T = D->getType();
12426  const bool IsArray = T->isArrayType();
12427  const bool IsFunction = T->isFunctionType();
12428 
12429  // Address of function is used to silence the function warning.
12430  if (IsAddressOf && IsFunction) {
12431  return;
12432  }
12433 
12434  // Found nothing.
12435  if (!IsAddressOf && !IsFunction && !IsArray)
12436  return;
12437 
12438  // Pretty print the expression for the diagnostic.
12439  std::string Str;
12440  llvm::raw_string_ostream S(Str);
12441  E->printPretty(S, nullptr, getPrintingPolicy());
12442 
12443  unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12444  : diag::warn_impcast_pointer_to_bool;
12445  enum {
12446  AddressOf,
12447  FunctionPointer,
12448  ArrayPointer
12449  } DiagType;
12450  if (IsAddressOf)
12451  DiagType = AddressOf;
12452  else if (IsFunction)
12453  DiagType = FunctionPointer;
12454  else if (IsArray)
12455  DiagType = ArrayPointer;
12456  else
12457  llvm_unreachable("Could not determine diagnostic.");
12458  Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12459  << Range << IsEqual;
12460 
12461  if (!IsFunction)
12462  return;
12463 
12464  // Suggest '&' to silence the function warning.
12465  Diag(E->getExprLoc(), diag::note_function_warning_silence)
12467 
12468  // Check to see if '()' fixit should be emitted.
12469  QualType ReturnType;
12470  UnresolvedSet<4> NonTemplateOverloads;
12471  tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12472  if (ReturnType.isNull())
12473  return;
12474 
12475  if (IsCompare) {
12476  // There are two cases here. If there is null constant, the only suggest
12477  // for a pointer return type. If the null is 0, then suggest if the return
12478  // type is a pointer or an integer type.
12479  if (!ReturnType->isPointerType()) {
12480  if (NullKind == Expr::NPCK_ZeroExpression ||
12481  NullKind == Expr::NPCK_ZeroLiteral) {
12482  if (!ReturnType->isIntegerType())
12483  return;
12484  } else {
12485  return;
12486  }
12487  }
12488  } else { // !IsCompare
12489  // For function to bool, only suggest if the function pointer has bool
12490  // return type.
12491  if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12492  return;
12493  }
12494  Diag(E->getExprLoc(), diag::note_function_to_function_call)
12495  << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12496 }
12497 
12498 /// Diagnoses "dangerous" implicit conversions within the given
12499 /// expression (which is a full expression). Implements -Wconversion
12500 /// and -Wsign-compare.
12501 ///
12502 /// \param CC the "context" location of the implicit conversion, i.e.
12503 /// the most location of the syntactic entity requiring the implicit
12504 /// conversion
12505 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12506  // Don't diagnose in unevaluated contexts.
12507  if (isUnevaluatedContext())
12508  return;
12509 
12510  // Don't diagnose for value- or type-dependent expressions.
12511  if (E->isTypeDependent() || E->isValueDependent())
12512  return;
12513 
12514  // Check for array bounds violations in cases where the check isn't triggered
12515  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12516  // ArraySubscriptExpr is on the RHS of a variable initialization.
12517  CheckArrayAccess(E);
12518 
12519  // This is not the right CC for (e.g.) a variable initialization.
12520  AnalyzeImplicitConversions(*this, E, CC);
12521 }
12522 
12523 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12524 /// Input argument E is a logical expression.
12525 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12526  ::CheckBoolLikeConversion(*this, E, CC);
12527 }
12528 
12529 /// Diagnose when expression is an integer constant expression and its evaluation
12530 /// results in integer overflow
12531 void Sema::CheckForIntOverflow (Expr *E) {
12532  // Use a work list to deal with nested struct initializers.
12533  SmallVector<Expr *, 2> Exprs(1, E);
12534 
12535  do {
12536  Expr *OriginalE = Exprs.pop_back_val();
12537  Expr *E = OriginalE->IgnoreParenCasts();
12538 
12539  if (isa<BinaryOperator>(E)) {
12540  E->EvaluateForOverflow(Context);
12541  continue;
12542  }
12543 
12544  if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12545  Exprs.append(InitList->inits().begin(), InitList->inits().end());
12546  else if (isa<ObjCBoxedExpr>(OriginalE))
12547  E->EvaluateForOverflow(Context);
12548  else if (auto Call = dyn_cast<CallExpr>(E))
12549  Exprs.append(Call->arg_begin(), Call->arg_end());
12550  else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12551  Exprs.append(Message->arg_begin(), Message->arg_end());
12552  } while (!Exprs.empty());
12553 }
12554 
12555 namespace {
12556 
12557 /// Visitor for expressions which looks for unsequenced operations on the
12558 /// same object.
12559 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12561 
12562  /// A tree of sequenced regions within an expression. Two regions are
12563  /// unsequenced if one is an ancestor or a descendent of the other. When we
12564  /// finish processing an expression with sequencing, such as a comma
12565  /// expression, we fold its tree nodes into its parent, since they are
12566  /// unsequenced with respect to nodes we will visit later.
12567  class SequenceTree {
12568  struct Value {
12569  explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12570  unsigned Parent : 31;
12571  unsigned Merged : 1;
12572  };
12573  SmallVector<Value, 8> Values;
12574 
12575  public:
12576  /// A region within an expression which may be sequenced with respect
12577  /// to some other region.
12578  class Seq {
12579  friend class SequenceTree;
12580 
12581  unsigned Index;
12582 
12583  explicit Seq(unsigned N) : Index(N) {}
12584 
12585  public:
12586  Seq() : Index(0) {}
12587  };
12588 
12589  SequenceTree() { Values.push_back(Value(0)); }
12590  Seq root() const { return Seq(0); }
12591 
12592  /// Create a new sequence of operations, which is an unsequenced
12593  /// subset of \p Parent. This sequence of operations is sequenced with
12594  /// respect to other children of \p Parent.
12595  Seq allocate(Seq Parent) {
12596  Values.push_back(Value(Parent.Index));
12597  return Seq(Values.size() - 1);
12598  }
12599 
12600  /// Merge a sequence of operations into its parent.
12601  void merge(Seq S) {
12602  Values[S.Index].Merged = true;
12603  }
12604 
12605  /// Determine whether two operations are unsequenced. This operation
12606  /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12607  /// should have been merged into its parent as appropriate.
12608  bool isUnsequenced(Seq Cur, Seq Old) {
12609  unsigned C = representative(Cur.Index);
12610  unsigned Target = representative(Old.Index);
12611  while (C >= Target) {
12612  if (C == Target)
12613  return true;
12614  C = Values[C].Parent;
12615  }
12616  return false;
12617  }
12618 
12619  private:
12620  /// Pick a representative for a sequence.
12621  unsigned representative(unsigned K) {
12622  if (Values[K].Merged)
12623  // Perform path compression as we go.
12624  return Values[K].Parent = representative(Values[K].Parent);
12625  return K;
12626  }
12627  };
12628 
12629  /// An object for which we can track unsequenced uses.
12630  using Object = const NamedDecl *;
12631 
12632  /// Different flavors of object usage which we track. We only track the
12633  /// least-sequenced usage of each kind.
12634  enum UsageKind {
12635  /// A read of an object. Multiple unsequenced reads are OK.
12636  UK_Use,
12637 
12638  /// A modification of an object which is sequenced before the value
12639  /// computation of the expression, such as ++n in C++.
12640  UK_ModAsValue,
12641 
12642  /// A modification of an object which is not sequenced before the value
12643  /// computation of the expression, such as n++.
12644  UK_ModAsSideEffect,
12645 
12646  UK_Count = UK_ModAsSideEffect + 1
12647  };
12648 
12649  /// Bundle together a sequencing region and the expression corresponding
12650  /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
12651  struct Usage {
12652  const Expr *UsageExpr;
12653  SequenceTree::Seq Seq;
12654 
12655  Usage() : UsageExpr(nullptr), Seq() {}
12656  };
12657 
12658  struct UsageInfo {
12659  Usage Uses[UK_Count];
12660 
12661  /// Have we issued a diagnostic for this object already?
12662  bool Diagnosed;
12663 
12664  UsageInfo() : Uses(), Diagnosed(false) {}
12665  };
12666  using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12667 
12668  Sema &SemaRef;
12669 
12670  /// Sequenced regions within the expression.
12671  SequenceTree Tree;
12672 
12673  /// Declaration modifications and references which we have seen.
12674  UsageInfoMap UsageMap;
12675 
12676  /// The region we are currently within.
12677  SequenceTree::Seq Region;
12678 
12679  /// Filled in with declarations which were modified as a side-effect
12680  /// (that is, post-increment operations).
12681  SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12682 
12683  /// Expressions to check later. We defer checking these to reduce
12684  /// stack usage.
12686 
12687  /// RAII object wrapping the visitation of a sequenced subexpression of an
12688  /// expression. At the end of this process, the side-effects of the evaluation
12689  /// become sequenced with respect to the value computation of the result, so
12690  /// we downgrade any UK_ModAsSideEffect within the evaluation to
12691  /// UK_ModAsValue.
12692  struct SequencedSubexpression {
12693  SequencedSubexpression(SequenceChecker &Self)
12694  : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12695  Self.ModAsSideEffect = &ModAsSideEffect;
12696  }
12697 
12698  ~SequencedSubexpression() {
12699  for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
12700  // Add a new usage with usage kind UK_ModAsValue, and then restore
12701  // the previous usage with UK_ModAsSideEffect (thus clearing it if
12702  // the previous one was empty).
12703  UsageInfo &UI = Self.UsageMap[M.first];
12704  auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
12705  Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
12706  SideEffectUsage = M.second;
12707  }
12708  Self.ModAsSideEffect = OldModAsSideEffect;
12709  }
12710 
12711  SequenceChecker &Self;
12712  SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12713  SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12714  };
12715 
12716  /// RAII object wrapping the visitation of a subexpression which we might
12717  /// choose to evaluate as a constant. If any subexpression is evaluated and
12718  /// found to be non-constant, this allows us to suppress the evaluation of
12719  /// the outer expression.
12720  class EvaluationTracker {
12721  public:
12722  EvaluationTracker(SequenceChecker &Self)
12723  : Self(Self), Prev(Self.EvalTracker) {
12724  Self.EvalTracker = this;
12725  }
12726 
12727  ~EvaluationTracker() {
12728  Self.EvalTracker = Prev;
12729  if (Prev)
12730  Prev->EvalOK &= EvalOK;
12731  }
12732 
12733  bool evaluate(const Expr *E, bool &Result) {
12734  if (!EvalOK || E->isValueDependent())
12735  return false;
12736  EvalOK = E->EvaluateAsBooleanCondition(
12737  Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12738  return EvalOK;
12739  }
12740 
12741  private:
12742  SequenceChecker &Self;
12743  EvaluationTracker *Prev;
12744  bool EvalOK = true;
12745  } *EvalTracker = nullptr;
12746 
12747  /// Find the object which is produced by the specified expression,
12748  /// if any.
12749  Object getObject(const Expr *E, bool Mod) const {
12750  E = E->IgnoreParenCasts();
12751  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12752  if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12753  return getObject(UO->getSubExpr(), Mod);
12754  } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12755  if (BO->getOpcode() == BO_Comma)
12756  return getObject(BO->getRHS(), Mod);
12757  if (Mod && BO->isAssignmentOp())
12758  return getObject(BO->getLHS(), Mod);
12759  } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12760  // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12761  if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12762  return ME->getMemberDecl();
12763  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12764  // FIXME: If this is a reference, map through to its value.
12765  return DRE->getDecl();
12766  return nullptr;
12767  }
12768 
12769  /// Note that an object \p O was modified or used by an expression
12770  /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
12771  /// the object \p O as obtained via the \p UsageMap.
12772  void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
12773  // Get the old usage for the given object and usage kind.
12774  Usage &U = UI.Uses[UK];
12775  if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
12776  // If we have a modification as side effect and are in a sequenced
12777  // subexpression, save the old Usage so that we can restore it later
12778  // in SequencedSubexpression::~SequencedSubexpression.
12779  if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12780  ModAsSideEffect->push_back(std::make_pair(O, U));
12781  // Then record the new usage with the current sequencing region.
12782  U.UsageExpr = UsageExpr;
12783  U.Seq = Region;
12784  }
12785  }
12786 
12787  /// Check whether a modification or use of an object \p O in an expression
12788  /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
12789  /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
12790  /// \p IsModMod is true when we are checking for a mod-mod unsequenced
12791  /// usage and false we are checking for a mod-use unsequenced usage.
12792  void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
12793  UsageKind OtherKind, bool IsModMod) {
12794  if (UI.Diagnosed)
12795  return;
12796 
12797  const Usage &U = UI.Uses[OtherKind];
12798  if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
12799  return;
12800 
12801  const Expr *Mod = U.UsageExpr;
12802  const Expr *ModOrUse = UsageExpr;
12803  if (OtherKind == UK_Use)
12804  std::swap(Mod, ModOrUse);
12805 
12806  SemaRef.DiagRuntimeBehavior(
12807  Mod->getExprLoc(), {Mod, ModOrUse},
12808  SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12809  : diag::warn_unsequenced_mod_use)
12810  << O << SourceRange(ModOrUse->getExprLoc()));
12811  UI.Diagnosed = true;
12812  }
12813 
12814  // A note on note{Pre, Post}{Use, Mod}:
12815  //
12816  // (It helps to follow the algorithm with an expression such as
12817  // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
12818  // operations before C++17 and both are well-defined in C++17).
12819  //
12820  // When visiting a node which uses/modify an object we first call notePreUse
12821  // or notePreMod before visiting its sub-expression(s). At this point the
12822  // children of the current node have not yet been visited and so the eventual
12823  // uses/modifications resulting from the children of the current node have not
12824  // been recorded yet.
12825  //
12826  // We then visit the children of the current node. After that notePostUse or
12827  // notePostMod is called. These will 1) detect an unsequenced modification
12828  // as side effect (as in "k++ + k") and 2) add a new usage with the
12829  // appropriate usage kind.
12830  //
12831  // We also have to be careful that some operation sequences modification as
12832  // side effect as well (for example: || or ,). To account for this we wrap
12833  // the visitation of such a sub-expression (for example: the LHS of || or ,)
12834  // with SequencedSubexpression. SequencedSubexpression is an RAII object
12835  // which record usages which are modifications as side effect, and then
12836  // downgrade them (or more accurately restore the previous usage which was a
12837  // modification as side effect) when exiting the scope of the sequenced
12838  // subexpression.
12839 
12840  void notePreUse(Object O, const Expr *UseExpr) {
12841  UsageInfo &UI = UsageMap[O];
12842  // Uses conflict with other modifications.
12843  checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
12844  }
12845 
12846  void notePostUse(Object O, const Expr *UseExpr) {
12847  UsageInfo &UI = UsageMap[O];
12848  checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
12849  /*IsModMod=*/false);
12850  addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
12851  }
12852 
12853  void notePreMod(Object O, const Expr *ModExpr) {
12854  UsageInfo &UI = UsageMap[O];
12855  // Modifications conflict with other modifications and with uses.
12856  checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
12857  checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
12858  }
12859 
12860  void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
12861  UsageInfo &UI = UsageMap[O];
12862  checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
12863  /*IsModMod=*/true);
12864  addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
12865  }
12866 
12867 public:
12868  SequenceChecker(Sema &S, const Expr *E,
12870  : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12871  Visit(E);
12872  // Silence a -Wunused-private-field since WorkList is now unused.
12873  // TODO: Evaluate if it can be used, and if not remove it.
12874  (void)this->WorkList;
12875  }
12876 
12877  void VisitStmt(const Stmt *S) {
12878  // Skip all statements which aren't expressions for now.
12879  }
12880 
12881  void VisitExpr(const Expr *E) {
12882  // By default, just recurse to evaluated subexpressions.
12883  Base::VisitStmt(E);
12884  }
12885 
12886  void VisitCastExpr(const CastExpr *E) {
12887  Object O = Object();
12888  if (E->getCastKind() == CK_LValueToRValue)
12889  O = getObject(E->getSubExpr(), false);
12890 
12891  if (O)
12892  notePreUse(O, E);
12893  VisitExpr(E);
12894  if (O)
12895  notePostUse(O, E);
12896  }
12897 
12898  void VisitSequencedExpressions(const Expr *SequencedBefore,
12899  const Expr *SequencedAfter) {
12900  SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12901  SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12902  SequenceTree::Seq OldRegion = Region;
12903 
12904  {
12905  SequencedSubexpression SeqBefore(*this);
12906  Region = BeforeRegion;
12907  Visit(SequencedBefore);
12908  }
12909 
12910  Region = AfterRegion;
12911  Visit(SequencedAfter);
12912 
12913  Region = OldRegion;
12914 
12915  Tree.merge(BeforeRegion);
12916  Tree.merge(AfterRegion);
12917  }
12918 
12919  void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
12920  // C++17 [expr.sub]p1:
12921  // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12922  // expression E1 is sequenced before the expression E2.
12923  if (SemaRef.getLangOpts().CPlusPlus17)
12924  VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12925  else {
12926  Visit(ASE->getLHS());
12927  Visit(ASE->getRHS());
12928  }
12929  }
12930 
12931  void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12932  void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
12933  void VisitBinPtrMem(const BinaryOperator *BO) {
12934  // C++17 [expr.mptr.oper]p4:
12935  // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
12936  // the expression E1 is sequenced before the expression E2.
12937  if (SemaRef.getLangOpts().CPlusPlus17)
12938  VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12939  else {
12940  Visit(BO->getLHS());
12941  Visit(BO->getRHS());
12942  }
12943  }
12944 
12945  void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12946  void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
12947  void VisitBinShlShr(const BinaryOperator *BO) {
12948  // C++17 [expr.shift]p4:
12949  // The expression E1 is sequenced before the expression E2.
12950  if (SemaRef.getLangOpts().CPlusPlus17)
12951  VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12952  else {
12953  Visit(BO->getLHS());
12954  Visit(BO->getRHS());
12955  }
12956  }
12957 
12958  void VisitBinComma(const BinaryOperator *BO) {
12959  // C++11 [expr.comma]p1:
12960  // Every value computation and side effect associated with the left
12961  // expression is sequenced before every value computation and side
12962  // effect associated with the right expression.
12963  VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12964  }
12965 
12966  void VisitBinAssign(const BinaryOperator *BO) {
12967  SequenceTree::Seq RHSRegion;
12968  SequenceTree::Seq LHSRegion;
12969  if (SemaRef.getLangOpts().CPlusPlus17) {
12970  RHSRegion = Tree.allocate(Region);
12971  LHSRegion = Tree.allocate(Region);
12972  } else {
12973  RHSRegion = Region;
12974  LHSRegion = Region;
12975  }
12976  SequenceTree::Seq OldRegion = Region;
12977 
12978  // C++11 [expr.ass]p1:
12979  // [...] the assignment is sequenced after the value computation
12980  // of the right and left operands, [...]
12981  //
12982  // so check it before inspecting the operands and update the
12983  // map afterwards.
12984  Object O = getObject(BO->getLHS(), /*Mod=*/true);
12985  if (O)
12986  notePreMod(O, BO);
12987 
12988  if (SemaRef.getLangOpts().CPlusPlus17) {
12989  // C++17 [expr.ass]p1:
12990  // [...] The right operand is sequenced before the left operand. [...]
12991  {
12992  SequencedSubexpression SeqBefore(*this);
12993  Region = RHSRegion;
12994  Visit(BO->getRHS());
12995  }
12996 
12997  Region = LHSRegion;
12998  Visit(BO->getLHS());
12999 
13000  if (O && isa<CompoundAssignOperator>(BO))
13001  notePostUse(O, BO);
13002 
13003  } else {
13004  // C++11 does not specify any sequencing between the LHS and RHS.
13005  Region = LHSRegion;
13006  Visit(BO->getLHS());
13007 
13008  if (O && isa<CompoundAssignOperator>(BO))
13009  notePostUse(O, BO);
13010 
13011  Region = RHSRegion;
13012  Visit(BO->getRHS());
13013  }
13014 
13015  // C++11 [expr.ass]p1:
13016  // the assignment is sequenced [...] before the value computation of the
13017  // assignment expression.
13018  // C11 6.5.16/3 has no such rule.
13019  Region = OldRegion;
13020  if (O)
13021  notePostMod(O, BO,
13022  SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13023  : UK_ModAsSideEffect);
13024  if (SemaRef.getLangOpts().CPlusPlus17) {
13025  Tree.merge(RHSRegion);
13026  Tree.merge(LHSRegion);
13027  }
13028  }
13029 
13030  void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13031  VisitBinAssign(CAO);
13032  }
13033 
13034  void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13035  void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13036  void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13037  Object O = getObject(UO->getSubExpr(), true);
13038  if (!O)
13039  return VisitExpr(UO);
13040 
13041  notePreMod(O, UO);
13042  Visit(UO->getSubExpr());
13043  // C++11 [expr.pre.incr]p1:
13044  // the expression ++x is equivalent to x+=1
13045  notePostMod(O, UO,
13046  SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13047  : UK_ModAsSideEffect);
13048  }
13049 
13050  void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13051  void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13052  void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13053  Object O = getObject(UO->getSubExpr(), true);
13054  if (!O)
13055  return VisitExpr(UO);
13056 
13057  notePreMod(O, UO);
13058  Visit(UO->getSubExpr());
13059  notePostMod(O, UO, UK_ModAsSideEffect);
13060  }
13061 
13062  void VisitBinLOr(const BinaryOperator *BO) {
13063  // C++11 [expr.log.or]p2:
13064  // If the second expression is evaluated, every value computation and
13065  // side effect associated with the first expression is sequenced before
13066  // every value computation and side effect associated with the
13067  // second expression.
13068  SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13069  SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13070  SequenceTree::Seq OldRegion = Region;
13071 
13072  EvaluationTracker Eval(*this);
13073  {
13074  SequencedSubexpression Sequenced(*this);
13075  Region = LHSRegion;
13076  Visit(BO->getLHS());
13077  }
13078 
13079  // C++11 [expr.log.or]p1:
13080  // [...] the second operand is not evaluated if the first operand
13081  // evaluates to true.
13082  bool EvalResult = false;
13083  bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13084  bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13085  if (ShouldVisitRHS) {
13086  Region = RHSRegion;
13087  Visit(BO->getRHS());
13088  }
13089 
13090  Region = OldRegion;
13091  Tree.merge(LHSRegion);
13092  Tree.merge(RHSRegion);
13093  }
13094 
13095  void VisitBinLAnd(const BinaryOperator *BO) {
13096  // C++11 [expr.log.and]p2:
13097  // If the second expression is evaluated, every value computation and
13098  // side effect associated with the first expression is sequenced before
13099  // every value computation and side effect associated with the
13100  // second expression.
13101  SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13102  SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13103  SequenceTree::Seq OldRegion = Region;
13104 
13105  EvaluationTracker Eval(*this);
13106  {
13107  SequencedSubexpression Sequenced(*this);
13108  Region = LHSRegion;
13109  Visit(BO->getLHS());
13110  }
13111 
13112  // C++11 [expr.log.and]p1:
13113  // [...] the second operand is not evaluated if the first operand is false.
13114  bool EvalResult = false;
13115  bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13116  bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13117  if (ShouldVisitRHS) {
13118  Region = RHSRegion;
13119  Visit(BO->getRHS());
13120  }
13121 
13122  Region = OldRegion;
13123  Tree.merge(LHSRegion);
13124  Tree.merge(RHSRegion);
13125  }
13126 
13127  void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13128  // C++11 [expr.cond]p1:
13129  // [...] Every value computation and side effect associated with the first
13130  // expression is sequenced before every value computation and side effect
13131  // associated with the second or third expression.
13132  SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13133 
13134  // No sequencing is specified between the true and false expression.
13135  // However since exactly one of both is going to be evaluated we can
13136  // consider them to be sequenced. This is needed to avoid warning on
13137  // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13138  // both the true and false expressions because we can't evaluate x.
13139  // This will still allow us to detect an expression like (pre C++17)
13140  // "(x ? y += 1 : y += 2) = y".
13141  //
13142  // We don't wrap the visitation of the true and false expression with
13143  // SequencedSubexpression because we don't want to downgrade modifications
13144  // as side effect in the true and false expressions after the visition
13145  // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13146  // not warn between the two "y++", but we should warn between the "y++"
13147  // and the "y".
13148  SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13149  SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13150  SequenceTree::Seq OldRegion = Region;
13151 
13152  EvaluationTracker Eval(*this);
13153  {
13154  SequencedSubexpression Sequenced(*this);
13155  Region = ConditionRegion;
13156  Visit(CO->getCond());
13157  }
13158 
13159  // C++11 [expr.cond]p1:
13160  // [...] The first expression is contextually converted to bool (Clause 4).
13161  // It is evaluated and if it is true, the result of the conditional
13162  // expression is the value of the second expression, otherwise that of the
13163  // third expression. Only one of the second and third expressions is
13164  // evaluated. [...]
13165  bool EvalResult = false;
13166  bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13167  bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13168  bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13169  if (ShouldVisitTrueExpr) {
13170  Region = TrueRegion;
13171  Visit(CO->getTrueExpr());
13172  }
13173  if (ShouldVisitFalseExpr) {
13174  Region = FalseRegion;
13175  Visit(CO->getFalseExpr());
13176  }
13177 
13178  Region = OldRegion;
13179  Tree.merge(ConditionRegion);
13180  Tree.merge(TrueRegion);
13181  Tree.merge(FalseRegion);
13182  }
13183 
13184  void VisitCallExpr(const CallExpr *CE) {
13185  // C++11 [intro.execution]p15:
13186  // When calling a function [...], every value computation and side effect
13187  // associated with any argument expression, or with the postfix expression
13188  // designating the called function, is sequenced before execution of every
13189  // expression or statement in the body of the function [and thus before
13190  // the value computation of its result].
13191  SequencedSubexpression Sequenced(*this);
13193  [&] { Base::VisitCallExpr(CE); });
13194 
13195  // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13196  }
13197 
13198  void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13199  // This is a call, so all subexpressions are sequenced before the result.
13200  SequencedSubexpression Sequenced(*this);
13201 
13202  if (!CCE->isListInitialization())
13203  return VisitExpr(CCE);
13204 
13205  // In C++11, list initializations are sequenced.
13207  SequenceTree::Seq Parent = Region;
13209  E = CCE->arg_end();
13210  I != E; ++I) {
13211  Region = Tree.allocate(Parent);
13212  Elts.push_back(Region);
13213  Visit(*I);
13214  }
13215 
13216  // Forget that the initializers are sequenced.
13217  Region = Parent;
13218  for (unsigned I = 0; I < Elts.size(); ++I)
13219  Tree.merge(Elts[I]);
13220  }
13221 
13222  void VisitInitListExpr(const InitListExpr *ILE) {
13223  if (!SemaRef.getLangOpts().CPlusPlus11)
13224  return VisitExpr(ILE);
13225 
13226  // In C++11, list initializations are sequenced.
13228  SequenceTree::Seq Parent = Region;
13229  for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13230  const Expr *E = ILE->getInit(I);
13231  if (!E)
13232  continue;
13233  Region = Tree.allocate(Parent);
13234  Elts.push_back(Region);
13235  Visit(E);
13236  }
13237 
13238  // Forget that the initializers are sequenced.
13239  Region = Parent;
13240  for (unsigned I = 0; I < Elts.size(); ++I)
13241  Tree.merge(Elts[I]);
13242  }
13243 };
13244 
13245 } // namespace
13246 
13247 void Sema::CheckUnsequencedOperations(const Expr *E) {
13249  WorkList.push_back(E);
13250  while (!WorkList.empty()) {
13251  const Expr *Item = WorkList.pop_back_val();
13252  SequenceChecker(*this, Item, WorkList);
13253  }
13254 }
13255 
13256 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13257  bool IsConstexpr) {
13258  llvm::SaveAndRestore<bool> ConstantContext(
13259  isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13260  CheckImplicitConversions(E, CheckLoc);
13261  if (!E->isInstantiationDependent())
13262  CheckUnsequencedOperations(E);
13263  if (!IsConstexpr && !E->isValueDependent())
13264  CheckForIntOverflow(E);
13265  DiagnoseMisalignedMembers();
13266 }
13267 
13268 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13269  FieldDecl *BitField,
13270  Expr *Init) {
13271  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13272 }
13273 
13275  SourceLocation Loc) {
13276  if (!PType->isVariablyModifiedType())
13277  return;
13278  if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13279  diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13280  return;
13281  }
13282  if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13283  diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13284  return;
13285  }
13286  if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13287  diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13288  return;
13289  }
13290 
13291  const ArrayType *AT = S.Context.getAsArrayType(PType);
13292  if (!AT)
13293  return;
13294 
13295  if (AT->getSizeModifier() != ArrayType::Star) {
13297  return;
13298  }
13299 
13300  S.Diag(Loc, diag::err_array_star_in_function_definition);
13301 }
13302 
13303 /// CheckParmsForFunctionDef - Check that the parameters of the given
13304 /// function are appropriate for the definition of a function. This
13305 /// takes care of any checks that cannot be performed on the
13306 /// declaration itself, e.g., that the types of each of the function
13307 /// parameters are complete.
13309  bool CheckParameterNames) {
13310  bool HasInvalidParm = false;
13311  for (ParmVarDecl *Param : Parameters) {
13312  // C99 6.7.5.3p4: the parameters in a parameter type list in a
13313  // function declarator that is part of a function definition of
13314  // that function shall not have incomplete type.
13315  //
13316  // This is also C++ [dcl.fct]p6.
13317  if (!Param->isInvalidDecl() &&
13318  RequireCompleteType(Param->getLocation(), Param->getType(),
13319  diag::err_typecheck_decl_incomplete_type)) {
13320  Param->setInvalidDecl();
13321  HasInvalidParm = true;
13322  }
13323 
13324  // C99 6.9.1p5: If the declarator includes a parameter type list, the
13325  // declaration of each parameter shall include an identifier.
13326  if (CheckParameterNames &&
13327  Param->getIdentifier() == nullptr &&
13328  !Param->isImplicit() &&
13329  !getLangOpts().CPlusPlus)
13330  Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13331 
13332  // C99 6.7.5.3p12:
13333  // If the function declarator is not part of a definition of that
13334  // function, parameters may have incomplete type and may use the [*]
13335  // notation in their sequences of declarator specifiers to specify
13336  // variable length array types.
13337  QualType PType = Param->getOriginalType();
13338  // FIXME: This diagnostic should point the '[*]' if source-location
13339  // information is added for it.
13340  diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13341 
13342  // If the parameter is a c++ class type and it has to be destructed in the
13343  // callee function, declare the destructor so that it can be called by the
13344  // callee function. Do not perform any direct access check on the dtor here.
13345  if (!Param->isInvalidDecl()) {
13346  if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13347  if (!ClassDecl->isInvalidDecl() &&
13348  !ClassDecl->hasIrrelevantDestructor() &&
13349  !ClassDecl->isDependentContext() &&
13350  ClassDecl->isParamDestroyedInCallee()) {
13351  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13352  MarkFunctionReferenced(Param->getLocation(), Destructor);
13353  DiagnoseUseOfDecl(Destructor, Param->getLocation());
13354  }
13355  }
13356  }
13357 
13358  // Parameters with the pass_object_size attribute only need to be marked
13359  // constant at function definitions. Because we lack information about
13360  // whether we're on a declaration or definition when we're instantiating the
13361  // attribute, we need to check for constness here.
13362  if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13363  if (!Param->getType().isConstQualified())
13364  Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13365  << Attr->getSpelling() << 1;
13366 
13367  // Check for parameter names shadowing fields from the class.
13368  if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13369  // The owning context for the parameter should be the function, but we
13370  // want to see if this function's declaration context is a record.
13371  DeclContext *DC = Param->getDeclContext();
13372  if (DC && DC->isFunctionOrMethod()) {
13373  if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13374  CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13375  RD, /*DeclIsField*/ false);
13376  }
13377  }
13378  }
13379 
13380  return HasInvalidParm;
13381 }
13382 
13383 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
13384 /// or MemberExpr.
13385 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
13386  ASTContext &Context) {
13387  if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
13388  return Context.getDeclAlign(DRE->getDecl());
13389 
13390  if (const auto *ME = dyn_cast<MemberExpr>(E))
13391  return Context.getDeclAlign(ME->getMemberDecl());
13392 
13393  return TypeAlign;
13394 }
13395 
13396 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13397 /// pointer cast increases the alignment requirements.
13399  // This is actually a lot of work to potentially be doing on every
13400  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13401  if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13402  return;
13403 
13404  // Ignore dependent types.
13405  if (T->isDependentType() || Op->getType()->isDependentType())
13406  return;
13407 
13408  // Require that the destination be a pointer type.
13409  const PointerType *DestPtr = T->getAs<PointerType>();
13410  if (!DestPtr) return;
13411 
13412  // If the destination has alignment 1, we're done.
13413  QualType DestPointee = DestPtr->getPointeeType();
13414  if (DestPointee->isIncompleteType()) return;
13415  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13416  if (DestAlign.isOne()) return;
13417 
13418  // Require that the source be a pointer type.
13419  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13420  if (!SrcPtr) return;
13421  QualType SrcPointee = SrcPtr->getPointeeType();
13422 
13423  // Whitelist casts from cv void*. We already implicitly
13424  // whitelisted casts to cv void*, since they have alignment 1.
13425  // Also whitelist casts involving incomplete types, which implicitly
13426  // includes 'void'.
13427  if (SrcPointee->isIncompleteType()) return;
13428 
13429  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
13430 
13431  if (auto *CE = dyn_cast<CastExpr>(Op)) {
13432  if (CE->getCastKind() == CK_ArrayToPointerDecay)
13433  SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13434  } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13435  if (UO->getOpcode() == UO_AddrOf)
13436  SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13437  }
13438 
13439  if (SrcAlign >= DestAlign) return;
13440 
13441  Diag(TRange.getBegin(), diag::warn_cast_align)
13442  << Op->getType() << T
13443  << static_cast<unsigned>(SrcAlign.getQuantity())
13444  << static_cast<unsigned>(DestAlign.getQuantity())
13445  << TRange << Op->getSourceRange();
13446 }
13447 
13448 /// Check whether this array fits the idiom of a size-one tail padded
13449 /// array member of a struct.
13450 ///
13451 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13452 /// commonly used to emulate flexible arrays in C89 code.
13453 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13454  const NamedDecl *ND) {
13455  if (Size != 1 || !ND) return false;
13456 
13457  const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13458  if (!FD) return false;
13459 
13460  // Don't consider sizes resulting from macro expansions or template argument
13461  // substitution to form C89 tail-padded arrays.
13462 
13463  TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13464  while (TInfo) {
13465  TypeLoc TL = TInfo->getTypeLoc();
13466  // Look through typedefs.
13467  if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13468  const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13469  TInfo = TDL->getTypeSourceInfo();
13470  continue;
13471  }
13473  const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13474  if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13475  return false;
13476  }
13477  break;
13478  }
13479 
13480  const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13481  if (!RD) return false;
13482  if (RD->isUnion()) return false;
13483  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13484  if (!CRD->isStandardLayout()) return false;
13485  }
13486 
13487  // See if this is the last field decl in the record.
13488  const Decl *D = FD;
13489  while ((D = D->getNextDeclInContext()))
13490  if (isa<FieldDecl>(D))
13491  return false;
13492  return true;
13493 }
13494 
13495 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13496  const ArraySubscriptExpr *ASE,
13497  bool AllowOnePastEnd, bool IndexNegated) {
13498  // Already diagnosed by the constant evaluator.
13499  if (isConstantEvaluated())
13500  return;
13501 
13502  IndexExpr = IndexExpr->IgnoreParenImpCasts();
13503  if (IndexExpr->isValueDependent())
13504  return;
13505 
13506  const Type *EffectiveType =
13507  BaseExpr->getType()->getPointeeOrArrayElementType();
13508  BaseExpr = BaseExpr->IgnoreParenCasts();
13509  const ConstantArrayType *ArrayTy =
13510  Context.getAsConstantArrayType(BaseExpr->getType());
13511 
13512  if (!ArrayTy)
13513  return;
13514 
13515  const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13516  if (EffectiveType->isDependentType() || BaseType->isDependentType())
13517  return;
13518 
13519  Expr::EvalResult Result;
13520  if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13521  return;
13522 
13523  llvm::APSInt index = Result.Val.getInt();
13524  if (IndexNegated)
13525  index = -index;
13526 
13527  const NamedDecl *ND = nullptr;
13528  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13529  ND = DRE->getDecl();
13530  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13531  ND = ME->getMemberDecl();
13532 
13533  if (index.isUnsigned() || !index.isNegative()) {
13534  // It is possible that the type of the base expression after
13535  // IgnoreParenCasts is incomplete, even though the type of the base
13536  // expression before IgnoreParenCasts is complete (see PR39746 for an
13537  // example). In this case we have no information about whether the array
13538  // access exceeds the array bounds. However we can still diagnose an array
13539  // access which precedes the array bounds.
13540  if (BaseType->isIncompleteType())
13541  return;
13542 
13543  llvm::APInt size = ArrayTy->getSize();
13544  if (!size.isStrictlyPositive())
13545  return;
13546 
13547  if (BaseType != EffectiveType) {
13548  // Make sure we're comparing apples to apples when comparing index to size
13549  uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13550  uint64_t array_typesize = Context.getTypeSize(BaseType);
13551  // Handle ptrarith_typesize being zero, such as when casting to void*
13552  if (!ptrarith_typesize) ptrarith_typesize = 1;
13553  if (ptrarith_typesize != array_typesize) {
13554  // There's a cast to a different size type involved
13555  uint64_t ratio = array_typesize / ptrarith_typesize;
13556  // TODO: Be smarter about handling cases where array_typesize is not a
13557  // multiple of ptrarith_typesize
13558  if (ptrarith_typesize * ratio == array_typesize)
13559  size *= llvm::APInt(size.getBitWidth(), ratio);
13560  }
13561  }
13562 
13563  if (size.getBitWidth() > index.getBitWidth())
13564  index = index.zext(size.getBitWidth());
13565  else if (size.getBitWidth() < index.getBitWidth())
13566  size = size.zext(index.getBitWidth());
13567 
13568  // For array subscripting the index must be less than size, but for pointer
13569  // arithmetic also allow the index (offset) to be equal to size since
13570  // computing the next address after the end of the array is legal and
13571  // commonly done e.g. in C++ iterators and range-based for loops.
13572  if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13573  return;
13574 
13575  // Also don't warn for arrays of size 1 which are members of some
13576  // structure. These are often used to approximate flexible arrays in C89
13577  // code.
13578  if (IsTailPaddedMemberArray(*this, size, ND))
13579  return;
13580 
13581  // Suppress the warning if the subscript expression (as identified by the
13582  // ']' location) and the index expression are both from macro expansions
13583  // within a system header.
13584  if (ASE) {
13585  SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13586  ASE->getRBracketLoc());
13587  if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13588  SourceLocation IndexLoc =
13589  SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13590  if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13591  return;
13592  }
13593  }
13594 
13595  unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13596  if (ASE)
13597  DiagID = diag::warn_array_index_exceeds_bounds;
13598 
13599  DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13600  PDiag(DiagID) << index.toString(10, true)
13601  << size.toString(10, true)
13602  << (unsigned)size.getLimitedValue(~0U)
13603  << IndexExpr->getSourceRange());
13604  } else {
13605  unsigned DiagID = diag::warn_array_index_precedes_bounds;
13606  if (!ASE) {
13607  DiagID = diag::warn_ptr_arith_precedes_bounds;
13608  if (index.isNegative()) index = -index;
13609  }
13610 
13611  DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13612  PDiag(DiagID) << index.toString(10, true)
13613  << IndexExpr->getSourceRange());
13614  }
13615 
13616  if (!ND) {
13617  // Try harder to find a NamedDecl to point at in the note.
13618  while (const ArraySubscriptExpr *ASE =
13619  dyn_cast<ArraySubscriptExpr>(BaseExpr))
13620  BaseExpr = ASE->getBase()->IgnoreParenCasts();
13621  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13622  ND = DRE->getDecl();
13623  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13624  ND = ME->getMemberDecl();
13625  }
13626 
13627  if (ND)
13628  DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13629  PDiag(diag::note_array_declared_here)
13630  << ND->getDeclName());
13631 }
13632 
13633 void Sema::CheckArrayAccess(const Expr *expr) {
13634  int AllowOnePastEnd = 0;
13635  while (expr) {
13636  expr = expr->IgnoreParenImpCasts();
13637  switch (expr->getStmtClass()) {
13638  case Stmt::ArraySubscriptExprClass: {
13639  const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13640  CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13641  AllowOnePastEnd > 0);
13642  expr = ASE->getBase();
13643  break;
13644  }
13645  case Stmt::MemberExprClass: {
13646  expr = cast<MemberExpr>(expr)->getBase();
13647  break;
13648  }
13649  case Stmt::OMPArraySectionExprClass: {
13650  const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13651  if (ASE->getLowerBound())
13652  CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13653  /*ASE=*/nullptr, AllowOnePastEnd > 0);
13654  return;
13655  }
13656  case Stmt::UnaryOperatorClass: {
13657  // Only unwrap the * and & unary operators
13658  const UnaryOperator *UO = cast<UnaryOperator>(expr);
13659  expr = UO->getSubExpr();
13660  switch (UO->getOpcode()) {
13661  case UO_AddrOf:
13662  AllowOnePastEnd++;
13663  break;
13664  case UO_Deref:
13665  AllowOnePastEnd--;
13666  break;
13667  default:
13668  return;
13669  }
13670  break;
13671  }
13672  case Stmt::ConditionalOperatorClass: {
13673  const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13674  if (const Expr *lhs = cond->getLHS())
13675  CheckArrayAccess(lhs);
13676  if (const Expr *rhs = cond->getRHS())
13677  CheckArrayAccess(rhs);
13678  return;
13679  }
13680  case Stmt::CXXOperatorCallExprClass: {
13681  const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13682  for (const auto *Arg : OCE->arguments())
13683  CheckArrayAccess(Arg);
13684  return;
13685  }
13686  default:
13687  return;
13688  }
13689  }
13690 }
13691 
13692 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13693 
13694 namespace {
13695 
13696 struct RetainCycleOwner {
13697  VarDecl *Variable = nullptr;
13698  SourceRange Range;
13699  SourceLocation Loc;
13700  bool Indirect = false;
13701 
13702  RetainCycleOwner() = default;
13703 
13704  void setLocsFrom(Expr *e) {
13705  Loc = e->getExprLoc();
13706  Range = e->getSourceRange();
13707  }
13708 };
13709 
13710 } // namespace
13711 
13712 /// Consider whether capturing the given variable can possibly lead to
13713 /// a retain cycle.
13714 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13715  // In ARC, it's captured strongly iff the variable has __strong
13716  // lifetime. In MRR, it's captured strongly if the variable is
13717  // __block and has an appropriate type.
13719  return false;
13720 
13721  owner.Variable = var;
13722  if (ref)
13723  owner.setLocsFrom(ref);
13724  return true;
13725 }
13726 
13727 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13728  while (true) {
13729  e = e->IgnoreParens();
13730  if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13731  switch (cast->getCastKind()) {
13732  case CK_BitCast:
13733  case CK_LValueBitCast:
13734  case CK_LValueToRValue:
13735  case CK_ARCReclaimReturnedObject:
13736  e = cast->getSubExpr();
13737  continue;
13738 
13739  default:
13740  return false;
13741  }
13742  }
13743 
13744  if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13745  ObjCIvarDecl *ivar = ref->getDecl();
13747  return false;
13748 
13749  // Try to find a retain cycle in the base.
13750  if (!findRetainCycleOwner(S, ref->getBase(), owner))
13751  return false;
13752 
13753  if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13754  owner.Indirect = true;
13755  return true;
13756  }
13757 
13758  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13759  VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13760  if (!var) return false;
13761  return considerVariable(var, ref, owner);
13762  }
13763 
13764  if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13765  if (member->isArrow()) return false;
13766 
13767  // Don't count this as an indirect ownership.
13768  e = member->getBase();
13769  continue;
13770  }
13771 
13772  if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13773  // Only pay attention to pseudo-objects on property references.
13774  ObjCPropertyRefExpr *pre
13775  = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13776  ->IgnoreParens());
13777  if (!pre) return false;
13778  if (pre->isImplicitProperty()) return false;
13779  ObjCPropertyDecl *property = pre->getExplicitProperty();
13780  if (!property->isRetaining() &&
13781  !(property->getPropertyIvarDecl() &&
13782  property->getPropertyIvarDecl()->getType()
13783  .getObjCLifetime() == Qualifiers::OCL_Strong))
13784  return false;
13785 
13786  owner.Indirect = true;
13787  if (pre->isSuperReceiver()) {
13788  owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13789  if (!owner.Variable)
13790  return false;
13791  owner.Loc = pre->getLocation();
13792  owner.Range = pre->getSourceRange();
13793  return true;
13794  }
13795  e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13796  ->getSourceExpr());
13797  continue;
13798  }
13799 
13800  // Array ivars?
13801 
13802  return false;
13803  }
13804 }
13805 
13806 namespace {
13807 
13808  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13809  ASTContext &Context;
13810  VarDecl *Variable;
13811  Expr *Capturer = nullptr;
13812  bool VarWillBeReased = false;
13813 
13814  FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13816  Context(Context), Variable(variable) {}
13817 
13818  void VisitDeclRefExpr(DeclRefExpr *ref) {
13819  if (ref->getDecl() == Variable && !Capturer)
13820  Capturer = ref;
13821  }
13822 
13823  void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13824  if (Capturer) return;
13825  Visit(ref->getBase());
13826  if (Capturer && ref->isFreeIvar())
13827  Capturer = ref;
13828  }
13829 
13830  void VisitBlockExpr(BlockExpr *block) {
13831  // Look inside nested blocks
13832  if (block->getBlockDecl()->capturesVariable(Variable))
13833  Visit(block->getBlockDecl()->getBody());
13834  }
13835 
13836  void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13837  if (Capturer) return;
13838  if (OVE->getSourceExpr())
13839  Visit(OVE->getSourceExpr());
13840  }
13841 
13842  void VisitBinaryOperator(BinaryOperator *BinOp) {
13843  if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13844  return;
13845  Expr *LHS = BinOp->getLHS();
13846  if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13847  if (DRE->getDecl() != Variable)
13848  return;
13849  if (Expr *RHS = BinOp->getRHS()) {
13850  RHS = RHS->IgnoreParenCasts();
13852  VarWillBeReased =
13853  (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13854  }
13855  }
13856  }
13857  };
13858 
13859 } // namespace
13860 
13861 /// Check whether the given argument is a block which captures a
13862 /// variable.
13863 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13864  assert(owner.Variable && owner.Loc.isValid());
13865 
13866  e = e->IgnoreParenCasts();
13867 
13868  // Look through [^{...} copy] and Block_copy(^{...}).
13869  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13870  Selector Cmd = ME->getSelector();
13871  if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13872  e = ME->getInstanceReceiver();
13873  if (!e)
13874  return nullptr;
13875  e = e->IgnoreParenCasts();
13876  }
13877  } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13878  if (CE->getNumArgs() == 1) {
13879  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13880  if (Fn) {
13881  const IdentifierInfo *FnI = Fn->getIdentifier();
13882  if (FnI && FnI->isStr("_Block_copy")) {
13883  e = CE->getArg(0)->IgnoreParenCasts();
13884  }
13885  }
13886  }
13887  }
13888 
13889  BlockExpr *block = dyn_cast<BlockExpr>(e);
13890  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13891  return nullptr;
13892 
13893  FindCaptureVisitor visitor(S.Context, owner.Variable);
13894  visitor.Visit(block->getBlockDecl()->getBody());
13895  return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13896 }
13897 
13898 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13899  RetainCycleOwner &owner) {
13900  assert(capturer);
13901  assert(owner.Variable && owner.Loc.isValid());
13902 
13903  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13904  << owner.Variable << capturer->getSourceRange();
13905  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13906  << owner.Indirect << owner.Range;
13907 }
13908 
13909 /// Check for a keyword selector that starts with the word 'add' or
13910 /// 'set'.
13911 static bool isSetterLikeSelector(Selector sel) {
13912  if (sel.isUnarySelector()) return false;
13913 
13914  StringRef str = sel.getNameForSlot(0);
13915  while (!str.empty() && str.front() == '_') str = str.substr(1);
13916  if (str.startswith("set"))
13917  str = str.substr(3);
13918  else if (str.startswith("add")) {
13919  // Specially whitelist 'addOperationWithBlock:'.
13920  if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13921  return false;
13922  str = str.substr(3);
13923  }
13924  else
13925  return false;
13926 
13927  if (str.empty()) return true;
13928  return !isLowercase(str.front());
13929 }
13930 
13932  ObjCMessageExpr *Message) {
13933  bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13934  Message->getReceiverInterface(),
13936  if (!IsMutableArray) {
13937  return None;
13938  }
13939 
13940  Selector Sel = Message->getSelector();
13941 
13943  S.NSAPIObj->getNSArrayMethodKind(Sel);
13944  if (!MKOpt) {
13945  return None;
13946  }
13947 
13948  NSAPI::NSArrayMethodKind MK = *MKOpt;
13949 
13950  switch (MK) {
13954  return 0;
13956  return 1;
13957 
13958  default:
13959  return None;
13960  }
13961 
13962  return None;
13963 }
13964 
13965 static
13967  ObjCMessageExpr *Message) {
13968  bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13969  Message->getReceiverInterface(),
13971  if (!IsMutableDictionary) {
13972  return None;
13973  }
13974 
13975  Selector Sel = Message->getSelector();
13976 
13978  S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13979  if (!MKOpt) {
13980  return None;
13981  }
13982 
13983  NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13984 
13985  switch (MK) {
13989  return 0;
13990 
13991  default:
13992  return None;
13993  }
13994 
13995  return None;
13996 }
13997 
13999  bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14000  Message->getReceiverInterface(),
14002 
14003  bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14004  Message->getReceiverInterface(),
14006  if (!IsMutableSet && !IsMutableOrderedSet) {
14007  return None;
14008  }
14009 
14010  Selector Sel = Message->getSelector();
14011 
14012  Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14013  if (!MKOpt) {
14014  return None;
14015  }
14016 
14017  NSAPI::NSSetMethodKind MK = *MKOpt;
14018 
14019  switch (MK) {
14024  return 0;
14026  return 1;
14027  }
14028 
14029  return None;
14030 }
14031 
14032 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14033  if (!Message->isInstanceMessage()) {
14034  return;
14035  }
14036 
14037  Optional<int> ArgOpt;
14038 
14039  if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14040  !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14041  !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14042  return;
14043  }
14044 
14045  int ArgIndex = *ArgOpt;
14046 
14047  Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14048  if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14049  Arg = OE->getSourceExpr()->IgnoreImpCasts();
14050  }
14051 
14052  if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14053  if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14054  if (ArgRE->isObjCSelfExpr()) {
14055  Diag(Message->getSourceRange().getBegin(),
14056  diag::warn_objc_circular_container)
14057  << ArgRE->getDecl() << StringRef("'super'");
14058  }
14059  }
14060  } else {
14061  Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14062 
14063  if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14064  Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14065  }
14066 
14067  if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14068  if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14069  if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14070  ValueDecl *Decl = ReceiverRE->getDecl();
14071  Diag(Message->getSourceRange().getBegin(),
14072  diag::warn_objc_circular_container)
14073  << Decl << Decl;
14074  if (!ArgRE->isObjCSelfExpr()) {
14075  Diag(Decl->getLocation(),
14076  diag::note_objc_circular_container_declared_here)
14077  << Decl;
14078  }
14079  }
14080  }
14081  } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14082  if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14083  if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14084  ObjCIvarDecl *Decl = IvarRE->getDecl();
14085  Diag(Message->getSourceRange().getBegin(),
14086  diag::warn_objc_circular_container)
14087  << Decl << Decl;
14088  Diag(Decl->getLocation(),
14089  diag::note_objc_circular_container_declared_here)
14090  << Decl;
14091  }
14092  }
14093  }
14094  }
14095 }
14096 
14097 /// Check a message send to see if it's likely to cause a retain cycle.
14099  // Only check instance methods whose selector looks like a setter.
14100  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14101  return;
14102 
14103  // Try to find a variable that the receiver is strongly owned by.
14104  RetainCycleOwner owner;
14106  if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14107  return;
14108  } else {
14110  owner.Variable = getCurMethodDecl()->getSelfDecl();
14111  owner.Loc = msg->getSuperLoc();
14112  owner.Range = msg->getSuperLoc();
14113  }
14114 
14115  // Check whether the receiver is captured by any of the arguments.
14116  const ObjCMethodDecl *MD = msg->getMethodDecl();
14117  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14118  if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14119  // noescape blocks should not be retained by the method.
14120  if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14121  continue;
14122  return diagnoseRetainCycle(*this, capturer, owner);
14123  }
14124  }
14125 }
14126 
14127 /// Check a property assign to see if it's likely to cause a retain cycle.
14128 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14129  RetainCycleOwner owner;
14130  if (!findRetainCycleOwner(*this, receiver, owner))
14131  return;
14132 
14133  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14134  diagnoseRetainCycle(*this, capturer, owner);
14135 }
14136 
14138  RetainCycleOwner Owner;
14139  if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14140  return;
14141 
14142  // Because we don't have an expression for the variable, we have to set the
14143  // location explicitly here.
14144  Owner.Loc = Var->getLocation();
14145  Owner.Range = Var->getSourceRange();
14146 
14147  if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14148  diagnoseRetainCycle(*this, Capturer, Owner);
14149 }
14150 
14152  Expr *RHS, bool isProperty) {
14153  // Check if RHS is an Objective-C object literal, which also can get
14154  // immediately zapped in a weak reference. Note that we explicitly
14155  // allow ObjCStringLiterals, since those are designed to never really die.
14156  RHS = RHS->IgnoreParenImpCasts();
14157 
14158  // This enum needs to match with the 'select' in
14159  // warn_objc_arc_literal_assign (off-by-1).
14161  if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14162  return false;
14163 
14164  S.Diag(Loc, diag::warn_arc_literal_assign)
14165  << (unsigned) Kind
14166  << (isProperty ? 0 : 1)
14167  << RHS->getSourceRange();
14168 
14169  return true;
14170 }
14171 
14174  Expr *RHS, bool isProperty) {
14175  // Strip off any implicit cast added to get to the one ARC-specific.
14176  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14177  if (cast->getCastKind() == CK_ARCConsumeObject) {
14178  S.Diag(Loc, diag::warn_arc_retained_assign)
14179  << (LT == Qualifiers::OCL_ExplicitNone)
14180  << (isProperty ? 0 : 1)
14181  << RHS->getSourceRange();
14182  return true;
14183  }
14184  RHS = cast->getSubExpr();
14185  }
14186 
14187  if (LT == Qualifiers::OCL_Weak &&
14188  checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14189  return true;
14190 
14191  return false;
14192 }
14193 
14195  QualType LHS, Expr *RHS) {
14197 
14199  return false;
14200 
14201  if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14202  return true;
14203 
14204  return false;
14205 }
14206 
14208  Expr *LHS, Expr *RHS) {
14209  QualType LHSType;
14210  // PropertyRef on LHS type need be directly obtained from
14211  // its declaration as it has a PseudoType.
14212  ObjCPropertyRefExpr *PRE
14213  = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14214  if (PRE && !PRE->isImplicitProperty()) {
14215  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14216  if (PD)
14217  LHSType = PD->getType();
14218  }
14219 
14220  if (LHSType.isNull())
14221  LHSType = LHS->getType();
14222 
14224 
14225  if (LT == Qualifiers::OCL_Weak) {
14226  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14227  getCurFunction()->markSafeWeakUse(LHS);
14228  }
14229 
14230  if (checkUnsafeAssigns(Loc, LHSType, RHS))
14231  return;
14232 
14233  // FIXME. Check for other life times.
14234  if (LT != Qualifiers::OCL_None)
14235  return;
14236 
14237  if (PRE) {
14238  if (PRE->isImplicitProperty())
14239  return;
14240  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14241  if (!PD)
14242  return;
14243 
14244  unsigned Attributes = PD->getPropertyAttributes();
14245  if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
14246  // when 'assign' attribute was not explicitly specified
14247  // by user, ignore it and rely on property type itself
14248  // for lifetime info.
14249  unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14250  if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
14251  LHSType->isObjCRetainableType())
14252  return;
14253 
14254  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14255  if (cast->getCastKind() == CK_ARCConsumeObject) {
14256  Diag(Loc, diag::warn_arc_retained_property_assign)
14257  << RHS->getSourceRange();
14258  return;
14259  }
14260  RHS = cast->getSubExpr();
14261  }
14262  }
14263  else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
14264  if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14265  return;
14266  }
14267  }
14268 }
14269 
14270 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14271 
14272 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14273  SourceLocation StmtLoc,
14274  const NullStmt *Body) {
14275  // Do not warn if the body is a macro that expands to nothing, e.g:
14276  //
14277  // #define CALL(x)
14278  // if (condition)
14279  // CALL(0);
14280  if (Body->hasLeadingEmptyMacro())
14281  return false;
14282 
14283  // Get line numbers of statement and body.
14284  bool StmtLineInvalid;
14285  unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14286  &StmtLineInvalid);
14287  if (StmtLineInvalid)
14288  return false;
14289 
14290  bool BodyLineInvalid;
14291  unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14292  &BodyLineInvalid);
14293  if (BodyLineInvalid)
14294  return false;
14295 
14296  // Warn if null statement and body are on the same line.
14297  if (StmtLine != BodyLine)
14298  return false;
14299 
14300  return true;
14301 }
14302 
14304  const Stmt *Body,
14305  unsigned DiagID) {
14306  // Since this is a syntactic check, don't emit diagnostic for template
14307  // instantiations, this just adds noise.
14308  if (CurrentInstantiationScope)
14309  return;
14310 
14311  // The body should be a null statement.
14312  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14313  if (!NBody)
14314  return;
14315 
14316  // Do the usual checks.
14317  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14318  return;
14319 
14320  Diag(NBody->getSemiLoc(), DiagID);
14321  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14322 }
14323 
14325  const Stmt *PossibleBody) {
14326  assert(!CurrentInstantiationScope); // Ensured by caller
14327 
14328  SourceLocation StmtLoc;
14329  const Stmt *Body;
14330  unsigned DiagID;
14331  if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14332  StmtLoc = FS->getRParenLoc();
14333  Body = FS->getBody();
14334  DiagID = diag::warn_empty_for_body;
14335  } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14336  StmtLoc = WS->getCond()->getSourceRange().getEnd();
14337  Body = WS->getBody();
14338  DiagID = diag::warn_empty_while_body;
14339  } else
14340  return; // Neither `for' nor `while'.
14341 
14342  // The body should be a null statement.
14343  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14344  if (!NBody)
14345  return;
14346 
14347  // Skip expensive checks if diagnostic is disabled.
14348  if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14349  return;
14350 
14351  // Do the usual checks.
14352  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14353  return;
14354 
14355  // `for(...);' and `while(...);' are popular idioms, so in order to keep
14356  // noise level low, emit diagnostics only if for/while is followed by a
14357  // CompoundStmt, e.g.:
14358  // for (int i = 0; i < n; i++);
14359  // {
14360  // a(i);
14361  // }
14362  // or if for/while is followed by a statement with more indentation
14363  // than for/while itself:
14364  // for (int i = 0; i < n; i++);
14365  // a(i);
14366  bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14367  if (!ProbableTypo) {
14368  bool BodyColInvalid;
14369  unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14370  PossibleBody->getBeginLoc(), &BodyColInvalid);
14371  if (BodyColInvalid)
14372  return;
14373 
14374  bool StmtColInvalid;
14375  unsigned StmtCol =
14376  SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14377  if (StmtColInvalid)
14378  return;
14379 
14380  if (BodyCol > StmtCol)
14381  ProbableTypo = true;
14382  }
14383 
14384  if (ProbableTypo) {
14385  Diag(NBody->getSemiLoc(), DiagID);
14386  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14387  }
14388 }
14389 
14390 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14391 
14392 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14393 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14394  SourceLocation OpLoc) {
14395  if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14396  return;
14397 
14398  if (inTemplateInstantiation())
14399  return;
14400 
14401  // Strip parens and casts away.
14402  LHSExpr = LHSExpr->IgnoreParenImpCasts();
14403  RHSExpr = RHSExpr->IgnoreParenImpCasts();
14404 
14405  // Check for a call expression
14406  const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14407  if (!CE || CE->getNumArgs() != 1)
14408  return;
14409 
14410  // Check for a call to std::move
14411  if (!CE->isCallToStdMove())
14412  return;
14413 
14414  // Get argument from std::move
14415  RHSExpr = CE->getArg(0);
14416 
14417  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14418  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14419 
14420  // Two DeclRefExpr's, check that the decls are the same.
14421  if (LHSDeclRef && RHSDeclRef) {
14422  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14423  return;
14424  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14425  RHSDeclRef->getDecl()->getCanonicalDecl())
14426  return;
14427 
14428  Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14429  << LHSExpr->getSourceRange()
14430  << RHSExpr->getSourceRange();
14431  return;
14432  }
14433 
14434  // Member variables require a different approach to check for self moves.
14435  // MemberExpr's are the same if every nested MemberExpr refers to the same
14436  // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14437  // the base Expr's are CXXThisExpr's.
14438  const Expr *LHSBase = LHSExpr;
14439  const Expr *RHSBase = RHSExpr;
14440  const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14441  const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14442  if (!LHSME || !RHSME)
14443  return;
14444 
14445  while (LHSME && RHSME) {
14446  if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14447  RHSME->getMemberDecl()->getCanonicalDecl())
14448  return;
14449 
14450  LHSBase = LHSME->getBase();
14451  RHSBase = RHSME->getBase();
14452  LHSME = dyn_cast<MemberExpr>(LHSBase);
14453  RHSME = dyn_cast<MemberExpr>(RHSBase);
14454  }
14455 
14456  LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14457  RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14458  if (LHSDeclRef && RHSDeclRef) {
14459  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14460  return;
14461  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14462  RHSDeclRef->getDecl()->getCanonicalDecl())
14463  return;
14464 
14465  Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14466  << LHSExpr->getSourceRange()
14467  << RHSExpr->getSourceRange();
14468  return;
14469  }
14470 
14471  if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14472  Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14473  << LHSExpr->getSourceRange()
14474  << RHSExpr->getSourceRange();
14475 }
14476 
14477 //===--- Layout compatibility ----------------------------------------------//
14478 
14479 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14480 
14481 /// Check if two enumeration types are layout-compatible.
14482 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14483  // C++11 [dcl.enum] p8:
14484  // Two enumeration types are layout-compatible if they have the same
14485  // underlying type.
14486  return ED1->isComplete() && ED2->isComplete() &&
14487  C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14488 }
14489 
14490 /// Check if two fields are layout-compatible.
14491 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14492  FieldDecl *Field2) {
14493  if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14494  return false;
14495 
14496  if (Field1->isBitField() != Field2->isBitField())
14497  return false;
14498 
14499  if (Field1->isBitField()) {
14500  // Make sure that the bit-fields are the same length.
14501  unsigned Bits1 = Field1->getBitWidthValue(C);
14502  unsigned Bits2 = Field2->getBitWidthValue(C);
14503 
14504  if (Bits1 != Bits2)
14505  return false;
14506  }
14507 
14508  return true;
14509 }
14510 
14511 /// Check if two standard-layout structs are layout-compatible.
14512 /// (C++11 [class.mem] p17)
14514  RecordDecl *RD2) {
14515  // If both records are C++ classes, check that base classes match.
14516  if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14517  // If one of records is a CXXRecordDecl we are in C++ mode,
14518  // thus the other one is a CXXRecordDecl, too.
14519  const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14520  // Check number of base classes.
14521  if (D1CXX->getNumBases() != D2CXX->getNumBases())
14522  return false;
14523 
14524  // Check the base classes.
14526  Base1 = D1CXX->bases_begin(),
14527  BaseEnd1 = D1CXX->bases_end(),
14528  Base2 = D2CXX->bases_begin();
14529  Base1 != BaseEnd1;
14530  ++Base1, ++Base2) {
14531  if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14532  return false;
14533  }
14534  } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14535  // If only RD2 is a C++ class, it should have zero base classes.
14536  if (D2CXX->getNumBases() > 0)
14537  return false;
14538  }
14539 
14540  // Check the fields.
14541  RecordDecl::field_iterator Field2 = RD2->field_begin(),
14542  Field2End = RD2->field_end(),
14543  Field1 = RD1->field_begin(),
14544  Field1End = RD1->field_end();
14545  for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14546  if (!isLayoutCompatible(C, *Field1, *Field2))
14547  return false;
14548  }
14549  if (Field1 != Field1End || Field2 != Field2End)
14550  return false;
14551 
14552  return true;
14553 }
14554 
14555 /// Check if two standard-layout unions are layout-compatible.
14556 /// (C++11 [class.mem] p18)
14558  RecordDecl *RD2) {
14559  llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14560  for (auto *Field2 : RD2->fields())
14561  UnmatchedFields.insert(Field2);
14562 
14563  for (auto *Field1 : RD1->fields()) {
14564  llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14565  I = UnmatchedFields.begin(),
14566  E = UnmatchedFields.end();
14567 
14568  for ( ; I != E; ++I) {
14569  if (isLayoutCompatible(C, Field1, *I)) {
14570  bool Result = UnmatchedFields.erase(*I);
14571  (void) Result;
14572  assert(Result);
14573  break;
14574  }
14575  }
14576  if (I == E)
14577  return false;
14578  }
14579 
14580  return UnmatchedFields.empty();
14581 }
14582 
14584  RecordDecl *RD2) {
14585  if (RD1->isUnion() != RD2->isUnion())
14586  return false;
14587 
14588  if (RD1->isUnion())
14589  return isLayoutCompatibleUnion(C, RD1, RD2);
14590  else
14591  return isLayoutCompatibleStruct(C, RD1, RD2);
14592 }
14593 
14594 /// Check if two types are layout-compatible in C++11 sense.
14596  if (T1.isNull() || T2.isNull())
14597  return false;
14598 
14599  // C++11 [basic.types] p11:
14600  // If two types T1 and T2 are the same type, then T1 and T2 are
14601  // layout-compatible types.
14602  if (C.hasSameType(T1, T2))
14603  return true;
14604 
14607 
14608  const Type::TypeClass TC1 = T1->getTypeClass();
14609  const Type::TypeClass TC2 = T2->getTypeClass();
14610 
14611  if (TC1 != TC2)
14612  return false;
14613 
14614  if (TC1 == Type::Enum) {
14615  return isLayoutCompatible(C,
14616  cast<EnumType>(T1)->getDecl(),
14617  cast<EnumType>(T2)->getDecl());
14618  } else if (TC1 == Type::Record) {
14619  if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14620  return false;
14621 
14622  return isLayoutCompatible(C,
14623  cast<RecordType>(T1)->getDecl(),
14624  cast<RecordType>(T2)->getDecl());
14625  }
14626 
14627  return false;
14628 }
14629 
14630 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14631 
14632 /// Given a type tag expression find the type tag itself.
14633 ///
14634 /// \param TypeExpr Type tag expression, as it appears in user's code.
14635 ///
14636 /// \param VD Declaration of an identifier that appears in a type tag.
14637 ///
14638 /// \param MagicValue Type tag magic value.
14639 ///
14640 /// \param isConstantEvaluated wether the evalaution should be performed in
14641 
14642 /// constant context.
14643 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14644  const ValueDecl **VD, uint64_t *MagicValue,
14645  bool isConstantEvaluated) {
14646  while(true) {
14647  if (!TypeExpr)
14648  return false;
14649 
14650  TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14651 
14652  switch (TypeExpr->getStmtClass()) {
14653  case Stmt::UnaryOperatorClass: {
14654  const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14655  if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14656  TypeExpr = UO->getSubExpr();
14657  continue;
14658  }
14659  return false;
14660  }
14661 
14662  case Stmt::DeclRefExprClass: {
14663  const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14664  *VD = DRE->getDecl();
14665  return true;
14666  }
14667 
14668  case Stmt::IntegerLiteralClass: {
14669  const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14670  llvm::APInt MagicValueAPInt = IL->getValue();
14671  if (MagicValueAPInt.getActiveBits() <= 64) {
14672  *MagicValue = MagicValueAPInt.getZExtValue();
14673  return true;
14674  } else
14675  return false;
14676  }
14677 
14678  case Stmt::BinaryConditionalOperatorClass:
14679  case Stmt::ConditionalOperatorClass: {
14680  const AbstractConditionalOperator *ACO =
14681  cast<AbstractConditionalOperator>(TypeExpr);
14682  bool Result;
14683  if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14684  isConstantEvaluated)) {
14685  if (Result)
14686  TypeExpr = ACO->getTrueExpr();
14687  else
14688  TypeExpr = ACO->getFalseExpr();
14689  continue;
14690  }
14691  return false;
14692  }
14693 
14694  case Stmt::BinaryOperatorClass: {
14695  const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14696  if (BO->getOpcode() == BO_Comma) {
14697  TypeExpr = BO->getRHS();
14698  continue;
14699  }
14700  return false;
14701  }
14702 
14703  default:
14704  return false;
14705  }
14706  }
14707 }
14708 
14709 /// Retrieve the C type corresponding to type tag TypeExpr.
14710 ///
14711 /// \param TypeExpr Expression that specifies a type tag.
14712 ///
14713 /// \param MagicValues Registered magic values.
14714 ///
14715 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14716 /// kind.
14717 ///
14718 /// \param TypeInfo Information about the corresponding C type.
14719 ///
14720 /// \param isConstantEvaluated wether the evalaution should be performed in
14721 /// constant context.
14722 ///
14723 /// \returns true if the corresponding C type was found.
14724 static bool GetMatchingCType(
14725  const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14726  const ASTContext &Ctx,
14727  const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14728  *MagicValues,
14729  bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14730  bool isConstantEvaluated) {
14731  FoundWrongKind = false;
14732 
14733  // Variable declaration that has type_tag_for_datatype attribute.
14734  const ValueDecl *VD = nullptr;
14735 
14736  uint64_t MagicValue;
14737 
14738  if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14739  return false;
14740 
14741  if (VD) {
14742  if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14743  if (I->getArgumentKind() != ArgumentKind) {
14744  FoundWrongKind = true;
14745  return false;
14746  }
14747  TypeInfo.Type = I->getMatchingCType();
14748  TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14749  TypeInfo.MustBeNull = I->getMustBeNull();
14750  return true;
14751  }
14752  return false;
14753  }
14754 
14755  if (!MagicValues)
14756  return false;
14757 
14758  llvm::DenseMap<Sema::TypeTagMagicValue,
14759  Sema::TypeTagData>::const_iterator I =
14760  MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14761  if (I == MagicValues->end())
14762  return false;
14763 
14764  TypeInfo = I->second;
14765  return true;
14766 }
14767 
14769  uint64_t MagicValue, QualType Type,
14770  bool LayoutCompatible,
14771  bool MustBeNull) {
14772  if (!TypeTagForDatatypeMagicValues)
14773  TypeTagForDatatypeMagicValues.reset(
14774  new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14775 
14776  TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14777  (*TypeTagForDatatypeMagicValues)[Magic] =
14778  TypeTagData(Type, LayoutCompatible, MustBeNull);
14779 }
14780 
14781 static bool IsSameCharType(QualType T1, QualType T2) {
14782  const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14783  if (!BT1)
14784  return false;
14785 
14786  const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14787  if (!BT2)
14788  return false;
14789 
14790  BuiltinType::Kind T1Kind = BT1->getKind();
14791  BuiltinType::Kind T2Kind = BT2->getKind();
14792 
14793  return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
14794  (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
14795  (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14796  (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14797 }
14798 
14799 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14800  const ArrayRef<const Expr *> ExprArgs,
14801  SourceLocation CallSiteLoc) {
14802  const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14803  bool IsPointerAttr = Attr->getIsPointer();
14804 
14805  // Retrieve the argument representing the 'type_tag'.
14806  unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14807  if (TypeTagIdxAST >= ExprArgs.size()) {
14808  Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14809  << 0 << Attr->getTypeTagIdx().getSourceIndex();
14810  return;
14811  }
14812  const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14813  bool FoundWrongKind;
14814  TypeTagData TypeInfo;
14815  if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14816  TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14817  TypeInfo, isConstantEvaluated())) {
14818  if (FoundWrongKind)
14819  Diag(TypeTagExpr->getExprLoc(),
14820  diag::warn_type_tag_for_datatype_wrong_kind)
14821  << TypeTagExpr->getSourceRange();
14822  return;
14823  }
14824 
14825  // Retrieve the argument representing the 'arg_idx'.
14826  unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14827  if (ArgumentIdxAST >= ExprArgs.size()) {
14828  Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14829  << 1 << Attr->getArgumentIdx().getSourceIndex();
14830  return;
14831  }
14832  const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14833  if (IsPointerAttr) {
14834  // Skip implicit cast of pointer to `void *' (as a function argument).
14835  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14836  if (ICE->getType()->isVoidPointerType() &&
14837  ICE->getCastKind() == CK_BitCast)
14838  ArgumentExpr = ICE->getSubExpr();
14839  }
14840  QualType ArgumentType = ArgumentExpr->getType();
14841 
14842  // Passing a `void*' pointer shouldn't trigger a warning.
14843  if (IsPointerAttr && ArgumentType->isVoidPointerType())
14844  return;
14845 
14846  if (TypeInfo.MustBeNull) {
14847  // Type tag with matching void type requires a null pointer.
14848  if (!ArgumentExpr->isNullPointerConstant(Context,
14850  Diag(ArgumentExpr->getExprLoc(),
14851  diag::warn_type_safety_null_pointer_required)
14852  << ArgumentKind->getName()
14853  << ArgumentExpr->getSourceRange()
14854  << TypeTagExpr->getSourceRange();
14855  }
14856  return;
14857  }
14858 
14859  QualType RequiredType = TypeInfo.Type;
14860  if (IsPointerAttr)
14861  RequiredType = Context.getPointerType(RequiredType);
14862 
14863  bool mismatch = false;
14864  if (!TypeInfo.LayoutCompatible) {
14865  mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14866 
14867  // C++11 [basic.fundamental] p1:
14868  // Plain char, signed char, and unsigned char are three distinct types.
14869  //
14870  // But we treat plain `char' as equivalent to `signed char' or `unsigned
14871  // char' depending on the current char signedness mode.
14872  if (mismatch)
14873  if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14874  RequiredType->getPointeeType())) ||
14875  (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14876  mismatch = false;
14877  } else
14878  if (IsPointerAttr)
14879  mismatch = !isLayoutCompatible(Context,
14880  ArgumentType->getPointeeType(),
14881  RequiredType->getPointeeType());
14882  else
14883  mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14884 
14885  if (mismatch)
14886  Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14887  << ArgumentType << ArgumentKind
14888  << TypeInfo.LayoutCompatible << RequiredType
14889  << ArgumentExpr->getSourceRange()
14890  << TypeTagExpr->getSourceRange();
14891 }
14892 
14893 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14894  CharUnits Alignment) {
14895  MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14896 }
14897 
14899  for (MisalignedMember &m : MisalignedMembers) {
14900  const NamedDecl *ND = m.RD;
14901  if (ND->getName().empty()) {
14902  if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14903  ND = TD;
14904  }
14905  Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14906  << m.MD << ND << m.E->getSourceRange();
14907  }
14908  MisalignedMembers.clear();
14909 }
14910 
14912  E = E->IgnoreParens();
14913  if (!T->isPointerType() && !T->isIntegerType())
14914  return;
14915  if (isa<UnaryOperator>(E) &&
14916  cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14917  auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14918  if (isa<MemberExpr>(Op)) {
14919  auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14920  if (MA != MisalignedMembers.end() &&
14921  (T->isIntegerType() ||
14922  (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14923  Context.getTypeAlignInChars(
14924  T->getPointeeType()) <= MA->Alignment))))
14925  MisalignedMembers.erase(MA);
14926  }
14927  }
14928 }
14929 
14931  Expr *E,
14932  llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14933  Action) {
14934  const auto *ME = dyn_cast<MemberExpr>(E);
14935  if (!ME)
14936  return;
14937 
14938  // No need to check expressions with an __unaligned-qualified type.
14939  if (E->getType().getQualifiers().hasUnaligned())
14940  return;
14941 
14942  // For a chain of MemberExpr like "a.b.c.d" this list
14943  // will keep FieldDecl's like [d, c, b].
14944  SmallVector<FieldDecl *, 4> ReverseMemberChain;
14945  const MemberExpr *TopME = nullptr;
14946  bool AnyIsPacked = false;
14947  do {
14948  QualType BaseType = ME->getBase()->getType();
14949  if (BaseType->isDependentType())
14950  return;
14951  if (ME->isArrow())
14952  BaseType = BaseType->getPointeeType();
14953  RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14954  if (RD->isInvalidDecl())
14955  return;
14956 
14957  ValueDecl *MD = ME->getMemberDecl();
14958  auto *FD = dyn_cast<FieldDecl>(MD);
14959  // We do not care about non-data members.
14960  if (!FD || FD->isInvalidDecl())
14961  return;
14962 
14963  AnyIsPacked =
14964  AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14965  ReverseMemberChain.push_back(FD);
14966 
14967  TopME = ME;
14968  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14969  } while (ME);
14970  assert(TopME && "We did not compute a topmost MemberExpr!");
14971 
14972  // Not the scope of this diagnostic.
14973  if (!AnyIsPacked)
14974  return;
14975 
14976  const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14977  const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14978  // TODO: The innermost base of the member expression may be too complicated.
14979  // For now, just disregard these cases. This is left for future
14980  // improvement.
14981  if (!DRE && !isa<CXXThisExpr>(TopBase))
14982  return;
14983 
14984  // Alignment expected by the whole expression.
14985  CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14986 
14987  // No need to do anything else with this case.
14988  if (ExpectedAlignment.isOne())
14989  return;
14990 
14991  // Synthesize offset of the whole access.
14992  CharUnits Offset;
14993  for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14994  I++) {
14995  Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14996  }
14997 
14998  // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14999  CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15000  ReverseMemberChain.back()->getParent()->getTypeForDecl());
15001 
15002  // The base expression of the innermost MemberExpr may give
15003  // stronger guarantees than the class containing the member.
15004  if (DRE && !TopME->isArrow()) {
15005  const ValueDecl *VD = DRE->getDecl();
15006  if (!VD->getType()->isReferenceType())
15007  CompleteObjectAlignment =
15008  std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15009  }
15010 
15011  // Check if the synthesized offset fulfills the alignment.
15012  if (Offset % ExpectedAlignment != 0 ||
15013  // It may fulfill the offset it but the effective alignment may still be
15014  // lower than the expected expression alignment.
15015  CompleteObjectAlignment < ExpectedAlignment) {
15016  // If this happens, we want to determine a sensible culprit of this.
15017  // Intuitively, watching the chain of member expressions from right to
15018  // left, we start with the required alignment (as required by the field
15019  // type) but some packed attribute in that chain has reduced the alignment.
15020  // It may happen that another packed structure increases it again. But if
15021  // we are here such increase has not been enough. So pointing the first
15022  // FieldDecl that either is packed or else its RecordDecl is,
15023  // seems reasonable.
15024  FieldDecl *FD = nullptr;
15025  CharUnits Alignment;
15026  for (FieldDecl *FDI : ReverseMemberChain) {
15027  if (FDI->hasAttr<PackedAttr>() ||
15028  FDI->getParent()->hasAttr<PackedAttr>()) {
15029  FD = FDI;
15030  Alignment = std::min(
15031  Context.getTypeAlignInChars(FD->getType()),
15032  Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15033  break;
15034  }
15035  }
15036  assert(FD && "We did not find a packed FieldDecl!");
15037  Action(E, FD->getParent(), FD, Alignment);
15038  }
15039 }
15040 
15041 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15042  using namespace std::placeholders;
15043 
15044  RefersToMemberWithReducedAlignment(
15045  rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15046  _2, _3, _4));
15047 }
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:614
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:1107
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static FormatStringType GetFormatStringType(const FormatAttr *Format)
bool isFloatingPoint() const
Definition: Type.h:2520
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:5593
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:219
VariadicCallType
Definition: Sema.h:10527
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:601
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:219
bool isCallToStdMove() const
Definition: Expr.h:2799
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
IntType getInt64Type() const
Definition: TargetInfo.h:304
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:180
static APFixedPoint getFromIntValue(const llvm::APSInt &Value, const FixedPointSemantics &DstFXSema, bool *Overflow=nullptr)
Create an APFixedPoint with a value equal to that of the provided integer, and in the same semantics ...
Definition: FixedPoint.cpp:250
const OptionalFlag & hasAlternativeForm() const
Definition: FormatString.h:589
QualType withConst() const
Retrieves a version of this type with const applied.
ObjCStringFormatFamily
CanQualType LongLongTy
Definition: ASTContext.h:1025
Represents a function declaration or definition.
Definition: Decl.h:1783
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
NamespaceDecl * getStdNamespace() const
const char * getSpelling() const
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:6824
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2692
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:1101
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:3872
Expr * getLHS() const
Definition: Expr.h:3780
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
SourceLocation getRParenLoc() const
Definition: Expr.h:2789
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:360
#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:1054
Smart pointer class that efficiently represents Objective-C method names.
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2614
QualType getElementType() const
Definition: Type.h:6173
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
CanQualType VoidPtrTy
Definition: ASTContext.h:1044
QualType getPointeeType() const
Definition: Type.h:2627
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
A (possibly-)qualified type.
Definition: Type.h:654
bool isBlockPointerType() const
Definition: Type.h:6512
StringKind getKind() const
Definition: Expr.h:1826
bool isArrayType() const
Definition: Type.h:6570
bool isMemberPointerType() const
Definition: Type.h:6552
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2919
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:665
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2702
SourceLocation getExprLoc() const
Definition: Expr.h:3465
Selector getSelector() const
Definition: ExprObjC.cpp:337
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:1984
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:581
static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
Defines enumerations for the type traits support.
FormatStringType
Definition: Sema.h:11730
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
bool isSuperReceiver() const
Definition: ExprObjC.h:776
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3435
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4451
bool containsNonAsciiOrNull() const
Definition: Expr.h:1844
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:2689
static Optional< int > GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message)
Expr * getBitWidth() const
Definition: Decl.h:2818
Kind getKind() const
Definition: Type.h:2495
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3422
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:1219
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:557
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:994
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:2941
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2021
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:358
static const Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:20
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:823
bool isRecordType() const
Definition: Type.h:6594
bool isAscii() const
Definition: Expr.h:1830
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
Expr * getBase() const
Definition: Expr.h:2913
static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall)
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:1958
const Type * getTypeForDecl() const
Definition: Decl.h:3053
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1411
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1311
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4086
arg_iterator arg_begin()
Definition: ExprCXX.h:1559
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:421
void setType(QualType t)
Definition: Expr.h:138
Opcode getOpcode() const
Definition: Expr.h:3469
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:1994
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
Strictly evaluate the expression.
Definition: Expr.h:612
Expr * getLowerBound()
Get lower bound of array section.
Definition: ExprOpenMP.h:90
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2918
The base class of the type hierarchy.
Definition: Type.h:1450
bool isVector() const
Definition: APValue.h:367
#define log2(__x)
Definition: tgmath.h:970
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanQualType LongTy
Definition: ASTContext.h:1025
bool isClkEventT() const
Definition: Type.h:6691
CanQualType getNSUIntegerType() const
Definition: ASTContext.h:1716
NSDictionaryMethodKind
Enumerates the NSDictionary/NSMutableDictionary methods used to generate literals and to apply some c...
Definition: NSAPI.h:96
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2889
Represent a C++ namespace.
Definition: Decl.h:497
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:49
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1422
Wrapper for source info for typedefs.
Definition: TypeLoc.h:670
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
QualType withConst() const
Definition: Type.h:826
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:707
const NestedNameSpecifier * Specifier
A container of type source information.
Definition: Type.h:6227
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call)
Returns true if pipe element type is different from the pointer.
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a fixed point va...
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4419
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:1040
QualType getElementType() const
Definition: Type.h:2910
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:592
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
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:1968
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
RangeSelector range(RangeSelector Begin, RangeSelector End)
Selects from the start of Begin and to the end of End.
Represents a variable declaration or definition.
Definition: Decl.h:820
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
QualType getReturnType() const
Definition: Decl.h:2445
ScopeFlags
ScopeFlags - These are bitfields that are or&#39;d together when creating a scope, which defines the sort...
Definition: Scope.h:44
DiagnosticsEngine & Diags
Definition: Sema.h:387
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3077
unsigned getNumParams() const
Definition: Type.h:3964
bool isEnumeralType() const
Definition: Type.h:6598
APFixedPoint getFixedPointMax(QualType Ty) const
Options for controlling the target.
Definition: TargetOptions.h:26
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:3684
APFloat & getComplexFloatReal()
Definition: APValue.h:426
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:7002
Extra information about a function prototype.
Definition: Type.h:3837
const OptionalFlag & hasThousandsGrouping() const
Definition: FormatString.h:584
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:25
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:138
bool isInvalidDecl() const
Definition: DeclBase.h:553
Like System, but searched after the system directories.
bool isAddrLabelDiff() const
Definition: APValue.h:372
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
Represents a parameter to a function.
Definition: Decl.h:1595
static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer type (but not a function pointer) and that the alignment is a power-of-two.
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1325
Defines the clang::Expr interface and subclasses for C++ expressions.
ObjCInterfaceDecl * NSDictionaryDecl
The declaration of the Objective-C NSDictionary class.
Definition: Sema.h:974
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.
static bool CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
Parse and apply any fixits to the source.
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2448
bool isVariableArrayType() const
Definition: Type.h:6582
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:3900
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:707
PipeType - OpenCL20.
Definition: Type.h:6159
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...
MatchKind
How well a given conversion specifier matches its argument.
Definition: FormatString.h:255
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:244
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
Represents a struct/union/class.
Definition: Decl.h:3748
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:725
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:272
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists...
Definition: Decl.h:3651
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3689
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:938
Expr * getFalseExpr() const
Definition: Expr.h:3778
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:284
SourceLocation getBegin() const
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:4081
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:3999
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
QualType getPointeeType() const
Definition: Type.h:2731
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:8412
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3971
Used for GCC&#39;s __alignof.
Definition: TypeTraits.h:106
bool isUTF8() const
Definition: Expr.h:1832
bool isCharType() const
Definition: Type.cpp:1871
field_range fields() const
Definition: Decl.h:3963
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:275
Represents a member of a struct/union/class.
Definition: Decl.h:2729
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:1902
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static int classifyConstantValue(Expr *Constant)
bool isReferenceType() const
Definition: Type.h:6516
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2712
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:417
IntType getSizeType() const
Definition: TargetInfo.h:271
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:1133
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6744
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:4116
__DEVICE__ int max(int __a, int __b)
Expr * getSubExpr()
Definition: Expr.h:3202
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
Definition: Expr.h:5971
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1054
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:723
static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
SourceLocation getQuestionLoc() const
Definition: Expr.h:3721
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:53
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
Definition: ExprObjC.h:188
unsigned getCharByteWidth() const
Definition: Expr.h:1824
bool isFloat() const
Definition: APValue.h:362
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:6433
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6881
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:580
bool isConstantEvaluated()
Definition: Sema.h:833
static Optional< int > GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message)
MatchKind matchesType(ASTContext &C, QualType argTy) const
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:252
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:125
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2399
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isUnarySelector() const
Describes an C or C++ initializer list.
Definition: Expr.h:4403
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, unsigned Start, unsigned End)
BinaryOperatorKind
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2807
ForStmt - This represents a &#39;for (init;cond;inc)&#39; stmt.
Definition: Stmt.h:2410
unsigned getLength() const
Definition: Expr.h:1823
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:3521
Represents the results of name lookup.
Definition: Lookup.h:46
PtrTy get() const
Definition: Ownership.h:170
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1309
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:588
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2289
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:7053
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS)
Check for comparisons of floating point operands using != and ==.
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:414
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:11835
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:853
child_range children()
Definition: Stmt.cpp:224
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:4300
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:671
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3434
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
Definition: Decl.h:3661
bool isComplexFloat() const
Definition: APValue.h:365
QualType getExceptionObjectType(QualType T) const
CompileCommand Cmd
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
llvm::Error Error
bool isComplexInt() const
Definition: APValue.h:364
bool isArrow() const
Definition: Expr.h:3020
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
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3000
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:50
Values of this type can never be null.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6256
StringKind
StringLiteral is followed by several trailing objects.
Definition: Expr.h:1733
field_iterator field_begin() const
Definition: Decl.cpp:4425
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:4031
NSSetMethodKind
Enumerates the NSMutableSet/NSOrderedSet methods used to apply some checks.
Definition: NSAPI.h:121
bool isInt() const
Definition: APValue.h:361
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:3150
base_class_iterator bases_begin()
Definition: DeclCXX.h:594
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
const LangOptions & getLangOpts() const
Definition: Sema.h:1324
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:1266
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:176
bool isScalarType() const
Definition: Type.h:6866
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:8666
An ordinary object is located at an address in memory.
Definition: Specifiers.h:141
bool Const(InterpState &S, CodePtr OpPC, const T &Arg)
Definition: Interp.h:294
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)...
Represents an ObjC class declaration.
Definition: DeclObjC.h:1186
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...
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3173
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:3443
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1817
Expression is a GNU-style __null constant.
Definition: Expr.h:728
static void diagnoseRetainCycle(Sema &S, Expr *capturer, RetainCycleOwner &owner)
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
PrimitiveDefaultInitializeKind
Definition: Type.h:1095
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
APSInt & getComplexIntReal()
Definition: APValue.h:410
CanQualType UnsignedCharTy
Definition: ASTContext.h:1026
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
std::string getRepresentativeTypeName(ASTContext &C) const
static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2975
const OptionalFlag & hasLeadingZeros() const
Definition: FormatString.h:590
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:1998
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
This object can be modified without requiring retains or releases.
Definition: Type.h:164
param_iterator param_begin()
Definition: Decl.h:2411
arg_iterator arg_end()
Definition: Expr.h:2747
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
APValue & getVectorElt(unsigned I)
Definition: APValue.h:454
The APFixedPoint class works similarly to APInt/APSInt in that it is a functional replacement for a s...
Definition: FixedPoint.h:95
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1857
NodeId Parent
Definition: ASTDiff.cpp:191
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:220
Provides definitions for the various language-specific address spaces.
Decl * getNextDeclInContext()
Definition: DeclBase.h:435
OpenMP 4.0 [2.4, Array Sections].
Definition: ExprOpenMP.h:44
const OptionalFlag & hasPlusPrefix() const
Definition: FormatString.h:588
bool hasAttr() const
Definition: DeclBase.h:542
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3732
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:336
StringRef getString() const
Definition: Expr.h:1794
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2560
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1690
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3754
bool isDynamicClass() const
Definition: DeclCXX.h:553
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3501
CastKind
CastKind - The kind of operation required for a conversion.
QualType getPromotionType() const
Return the integer type that enumerators should promote to.
Definition: Decl.h:3627
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:2372
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to...
Definition: Expr.cpp:2047
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:83
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:6932
arg_iterator arg_end()
Definition: ExprCXX.h:1560
SourceLocation getLocation() const
Definition: Expr.h:1255
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:3121
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
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, bool IgnoreStringsWithoutSpecifiers)
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
static bool IsShiftedByte(llvm::APSInt Value)
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
Scope * getCurScope() const
Retrieve the parser&#39;s current scope.
Definition: Sema.h:11904
unsigned Offset
Definition: Format.cpp:1827
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:3401
Exposes information about the current target.
Definition: TargetInfo.h:164
NSArrayMethodKind
Enumerates the NSArray/NSMutableArray methods used to generate literals and to apply some checks...
Definition: NSAPI.h:72
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we&#39;re targeting...
Expr * getCond() const
Definition: Expr.h:3769
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:212
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4675
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.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4037
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:619
This represents one expression.
Definition: Expr.h:108
static const IntegerLiteral * getIntegerLiteral(Expr *E)
Defines the clang::LangOptions interface.
const OptionalFlag & isLeftJustified() const
Definition: FormatString.h:587
SourceLocation End
Allow any unmodeled side effect.
Definition: Expr.h:615
Represents a character-granular source range.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:122
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2827
void setCallee(Expr *F)
Definition: Expr.h:2665
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
void EvaluateForOverflow(const ASTContext &Ctx) const
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:1313
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7067
bool isObjCRetainableType() const
Definition: Type.cpp:4060
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
Definition: Decl.cpp:1077
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...
#define V(N, I)
Definition: ASTContext.h:2941
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5579
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:88
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2649
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Expr * getCallee()
Definition: Expr.h:2663
unsigned getNumInits() const
Definition: Expr.h:4433
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3669
This scope corresponds to an SEH except.
Definition: Scope.h:124
bool isSignedInteger() const
Definition: Type.h:2512
Defines an enumeration for C++ overloaded operators.
bool isNullPtrType() const
Definition: Type.h:6802
field_iterator field_end() const
Definition: Decl.h:3966
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:304
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:6912
DeclContext * getDeclContext()
Definition: DeclBase.h:438
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:533
bool isAnyComplexType() const
Definition: Type.h:6602
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:434
CanQualType ShortTy
Definition: ASTContext.h:1025
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2681
const OptionalAmount & getFieldWidth() const
Definition: FormatString.h:436
void removeLocalConst()
Definition: Type.h:6350
void removeLocalVolatile()
Definition: Type.h:6358
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7919
Defines the clang::TypeLoc interface and its subclasses.
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:4143
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:1928
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
QualType getType() const
Definition: Expr.h:137
bool isFunctionOrMethod() const
Definition: DeclBase.h:1836
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isWide() const
Definition: Expr.h:1831
Expr * getElement(unsigned Index)
getElement - Return the Element at the specified index.
Definition: ExprObjC.h:230
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:431
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1156
static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call)
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1784
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:950
bool isInvalid() const
Definition: Ownership.h:166
SourceLocation getRBracketLoc() const
Definition: Expr.h:2516
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:2046
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:1401
Represents a GCC generic vector type.
Definition: Type.h:3235
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1234
static OpenCLAccessAttr * getOpenCLArgAccess(const Decl *D)
Returns OpenCL access qual.
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2912
unsigned getNumArgs() const
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6925
bool capturesVariable(const VarDecl *var) const
Definition: Decl.cpp:4570
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:6757
ValueDecl * getDecl()
Definition: Expr.h:1247
APSInt & getComplexIntImag()
Definition: APValue.h:418
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:1417
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:3371
QualType withoutLocalFastQualifiers() const
Definition: Type.h:882
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:415
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:432
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2497
QualType getType() const
Definition: DeclObjC.h:842
const SourceManager & SM
Definition: Format.cpp:1685
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:1725
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:265
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:1395
CanQualType SignedCharTy
Definition: ASTContext.h:1025
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:421
static CharSourceRange getCharRange(SourceRange R)
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6315
bool isVoidPointerType() const
Definition: Type.cpp:521
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
RecordDecl * getDecl() const
Definition: Type.h:4505
void toString(llvm::SmallVectorImpl< char > &Str) const
Definition: FixedPoint.cpp:176
static void adornObjCBoolConversionDiagWithTernaryFixit(Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition: Sema.h:11841
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)
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:754
EltType getEltType() const
Defines the clang::OpenCLOptions class.
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
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:160
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:1075
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:4067
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver. ...
Definition: ExprObjC.h:1382
CanQualType BuiltinFnTy
Definition: ASTContext.h:1046
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:171
Kind
QualType getCanonicalType() const
Definition: Type.h:6295
not a target-specific vector type
Definition: Type.h:3239
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5715
bool isImplicitProperty() const
Definition: ExprObjC.h:704
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
Definition: Expr.h:200
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:1331
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.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:423
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:3743
Encodes a location in the source.
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:1887
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:4521
SourceLocation getOperatorLoc() const
Definition: Expr.h:3466
llvm::APSInt APSInt
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6377
Expression is not a Null pointer constant.
Definition: Expr.h:712
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:826
Expr * getSubExpr() const
Definition: Expr.h:2076
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2166
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)
bool InRange(InterpState &S, CodePtr OpPC)
Definition: Interp.h:264
CastKind getCastKind() const
Definition: Expr.h:3196
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:266
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:358
APFloat & getFloat()
Definition: APValue.h:394
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:139
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1844
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1931
static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool)
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2466
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:1301
CanQualType FloatTy
Definition: ASTContext.h:1028
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2422
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:1835
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.
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:1944
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:5849
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:743
CanQualType VoidTy
Definition: ASTContext.h:1016
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
Class representing optional flags with location and representation information.
Definition: FormatString.h:33
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1540
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:158
Look up any declaration with any name.
Definition: Sema.h:3477
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1886
arg_range arguments()
Definition: Expr.h:2739
bool isObjCObjectPointerType() const
Definition: Type.h:6618
bool isAnyPointerType() const
Definition: Type.h:6508
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static bool isBlockPointer(Expr *Arg)
bool FormatStringHasSArg(const StringLiteral *FExpr)
llvm::APInt APInt
Definition: Integral.h:27
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:741
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3274
bool isFunctionProtoType() const
Definition: Type.h:2013
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:366
TypeClass getTypeClass() const
Definition: Type.h:1876
Used for C&#39;s _Alignof and C++&#39;s alignof.
Definition: TypeTraits.h:100
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3263
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2020
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3557
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:1356
static bool IsEnumConstOrFromMacro(Sema &S, Expr *E)
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:1977
bool isVectorType() const
Definition: Type.h:6606
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1166
Assigning into this object requires a lifetime extension.
Definition: Type.h:177
FixedPointSemantics getFixedPointSemantics(QualType Ty) const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclObjC.h:286
static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call)
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like &#39;memset(buf, sizeof(buf), 0)&#39;, which should have the last two arguments transpose...
We are currently in the filter expression of an SEH except block.
Definition: Scope.h:127
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2345
LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
Definition: CharInfo.h:99
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:975
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1022
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:224
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1371
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:560
Expr * getLHS() const
Definition: Expr.h:3474
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3654
static bool isObjCSignedCharBool(Sema &S, QualType Ty)
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:1260
CanQualType UnsignedShortTy
Definition: ASTContext.h:1026
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:3071
QualType withVolatile() const
Definition: Type.h:834
CanQualType CharTy
Definition: ASTContext.h:1018
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9608
bool isPipeType() const
Definition: Type.h:6710
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1297
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:130
Dataflow Directional Tag Classes.
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6844
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i...
std::string getAsString() const
getAsString - Retrieve the human-readable string for this name.
bool isValid() const
Return true if this is a valid SourceLocation object.
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
bool GT(InterpState &S, CodePtr OpPC)
Definition: Interp.h:245
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:5942
SourceLocation getLocation() const
Definition: ExprObjC.h:763
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:586
PropertyAttributeKind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:865
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:228
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:529
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments for this type.
Definition: Type.h:6059
APFixedPoint getFixedPointMin(QualType Ty) const
bool isSEHExceptScope() const
Determine whether this scope is a SEH &#39;__except&#39; block.
Definition: Scope.h:449
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:223
static bool isX86_32Builtin(unsigned BuiltinID)
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:10265
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:17264
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1027
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
SourceLocation getSemiLoc() const
Definition: Stmt.h:1308
The name of a declaration.
StmtClass getStmtClass() const
Definition: Stmt.h:1109
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:990
bool isBooleanType() const
Definition: Type.h:6894
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1513
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
Definition: Expr.h:719
U cast(CodeGen::Address addr)
Definition: Address.h:108
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.
Represents an enum.
Definition: Decl.h:3481
Expression is a C++11 nullptr.
Definition: Expr.h:725
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:593
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, bool IgnoreStringsWithoutSpecifiers=false)
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:1499
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
ConstEvaluatedExprVisitor - This class visits &#39;const Expr *&#39;s.
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:192
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:2053
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1143
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
SemaConvertVectorExpr - Handle __builtin_convertvector.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2995
param_iterator param_end()
Definition: Decl.h:2412
static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall)
llvm::APInt getValue() const
Definition: Expr.h:1430
bool isMacroID() const
Represents a pointer to an Objective C object.
Definition: Type.h:5951
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:152
unsigned getByteLength() const
Definition: Expr.h:1822
Pointer to a block type.
Definition: Type.h:2716
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
unsigned getIntWidth(QualType T) const
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2983
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:4495
Complex values, per C99 6.2.5p11.
Definition: Type.h:2554
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...
Iterator for iterating over Stmt * arrays that contain only T *.
Definition: Stmt.h:1064
static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call)
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2462
StringLiteralCheckType
bool isUTF32() const
Definition: Expr.h:1834
QualType getCanonicalTypeInternal() const
Definition: Type.h:2429
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:227
ObjCLiteralKind
Definition: Sema.h:3105
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:3690
bool isReserveIDT() const
Definition: Type.h:6699
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6811
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:1026
ArgType getArgType(ASTContext &Ctx) const
static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call)
arg_iterator arg_begin()
Definition: Expr.h:2744
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1084
T * getAttr() const
Definition: DeclBase.h:538
const llvm::APInt & getSize() const
Definition: Type.h:2958
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2108
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
Definition: Sema.cpp:1304
bool isAtomicType() const
Definition: Type.h:6631
static bool isKnownToHaveUnsignedValue(Expr *E)
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, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:545
bool isFunctionType() const
Definition: Type.h:6500
static unsigned RFT(unsigned t, bool shift=false, bool ForceQuad=false)
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:700
static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type. ...
ExtVectorType - Extended vector type.
Definition: Type.h:3354
const OptionalAmount & getPrecision() const
Definition: FormatString.h:569
Opcode getOpcode() const
Definition: Expr.h:2071
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3510
bool isInteger() const
Definition: Type.h:2508
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:2321
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1929
The template argument is a type.
Definition: TemplateBase.h:59
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:92
The conversion specifier and the argument type are compatible.
Definition: FormatString.h:261
const OptionalFlag & isPublic() const
Definition: FormatString.h:594
ObjCInterfaceDecl * NSArrayDecl
The declaration of the Objective-C NSArray class.
Definition: Sema.h:968
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
const Expr * getBase() const
Definition: ExprObjC.h:580
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3828
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:115
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
Represents a base class of a C++ class.
Definition: DeclCXX.h:145
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:144
AtomicArgumentOrder
Definition: Sema.h:4847
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2104
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:1931
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:546
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:6622
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2115
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
const OptionalFlag & hasSpacePrefix() const
Definition: FormatString.h:591
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2305
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:524
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
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:244
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:174
bool isQueueT() const
Definition: Type.h:6695
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
bool isFreeIvar() const
Definition: ExprObjC.h:585
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:3966
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:722
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\, const ASTContext *Context=nullptr) const
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:2836
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:6336
Provides definitions for the atomic synchronization scopes.
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool hasUnaligned() const
Definition: Type.h:299
APFloat & getComplexFloatImag()
Definition: APValue.h:434
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:1958
Represents a C++ struct/union/class.
Definition: DeclCXX.h:253
Compatible - the types are compatible according to the standard.
Definition: Sema.h:10603
Expr * getTrueExpr() const
Definition: Expr.h:3773
bool isVoidType() const
Definition: Type.h:6777
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:237
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:1818
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6283
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:3672
Expr * getRHS() const
Definition: Expr.h:3781
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1959
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
WhileStmt - This represents a &#39;while&#39; stmt.
Definition: Stmt.h:2226
static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall)
SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
ASTImporterLookupTable & LT
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:582
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:397
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
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:129
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2465
bool isVariadic() const
Definition: DeclObjC.h:428
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
SourceManager & getSourceManager() const
Definition: Sema.h:1329
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:263
__DEVICE__ int min(int __a, int __b)
static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1711
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2546
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3635
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:250
ExprResult ExprError()
Definition: Ownership.h:279
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:947
CanQualType IntTy
Definition: ASTContext.h:1025
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:2150
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, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1171
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:825
bool isUnion() const
Definition: Decl.h:3407
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
Expr * getRHS() const
Definition: Expr.h:3476
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:6504
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3517
SourceManager & SourceMgr
Definition: Sema.h:388
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:93
llvm::APSInt convertToInt(unsigned DstWidth, bool DstSign, bool *Overflow=nullptr) const
Return the integral part of this fixed point number, rounded towards zero.
Definition: FixedPoint.cpp:221
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:66
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:583
QualType getType() const
Definition: Decl.h:630
#define true
Definition: stdbool.h:16
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
bool isFloatingType() const
Definition: Type.cpp:2005
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:616
bool isUTF16() const
Definition: Expr.h:1833
const Expr * getBase() const
Definition: ExprObjC.h:756
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:385
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1531
This represents a decl that may have a name.
Definition: Decl.h:223
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
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:1017
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:380
CanQualType DoubleTy
Definition: ASTContext.h:1028
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:6538
bool isInStdNamespace() const
Definition: DeclBase.cpp:357
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition: ExprObjC.h:1248
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3242
Decl * getCalleeDecl()
Definition: Expr.h:2675
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3524
SourceLocation getBegin() const
Optional< ConversionSpecifier > getStandardSpecifier() const
const LangOptions & getLangOpts() const
Definition: ASTContext.h:724
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:2935
This class handles loading and caching of source files into memory.
bool isUnsignedInteger() const
Definition: Type.h:2516
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition: Types.cpp:147
APFixedPoint & getFixedPoint()
Definition: APValue.h:402
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Definition: Expr.h:710
Attr - This represents one attribute.
Definition: Attr.h:45
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
Definition: FormatString.h:264
SourceLocation getLocation() const
Definition: DeclBase.h:429
bool EQ(InterpState &S, CodePtr OpPC)
Definition: Interp.h:216
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:3162
LangStandard::Kind Std
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:12403
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6238
CanQualType OCLClkEventTy
Definition: ASTContext.h:1053
static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext)
Pseudo-evaluate the given integer expression, estimating the range of values it might take...
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:368
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1364
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2991
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
CanQualType UnsignedIntTy
Definition: ASTContext.h:1026
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:81
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1080
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
unsigned getVectorLength() const
Definition: APValue.h:462